根据对象键创建对象数组

时间:2017-01-24 20:42:35

标签: javascript arrays object

我有一些json数据要转换为应该具有以下结构的对象数组:

{
    "people": [{
        "key": ["2Anita", "1916"],
        "values": ["11"]
    }, {
        "key": ["2Anita", "1917"],
        "values": ["20"]
    },  {
        "key": ["2Anna", "1916"],
        "values": ["153"]
    }, {
        "key": ["2Anna", "1917"],
        "values": ["91"]
    }]
}

源数据具有以下结构:

var people = [{
        "key": ["2Anita", "1916"],
        "values": ["11"]
    }, {
        "key": ["2Anita", "1917"],
        "values": ["20"]
    },  {
        "key": ["2Ann", "1920"],
        "values": [".."]
    }, {
        "key": ["2Anna", "1916"],
        "values": ["153"]
    }, {
        "key": ["2Anna", "1917"],
        "values": ["91"]
    }, {
        "key": ["2Ann-Christin", "1916"],
        "values": [".."]
    }, {
        "key": ["2Ann-Christin", "1917"],
        "values": [".."]
    }]

var tempNames = [];
var names = [];

    //Creating array that holds every unique name
    people.forEach(function functionName(v, k) {
        if (tempNames.indexOf(v.key[0]) === -1) {
            tempNames.push(v.key[0])
        }
    });

    //Creating array with objects for each unique name
    tempNames.forEach(function(v, k) {
        names.push({
            name: v,
            years: [],
            born: []
        })
    });

这是我迄今取得的成就:

  var grouped = _.groupBy(people, function(num) {
        return num.key[0];
    });

    var j = 0;
    var n = _.each(grouped, function(val) {
        vm.names.push({
            name: val[0].key[0],
            years: [],
            born: []
        })
        for (var i = 0; i < val.length; i++) {
            vm.names[j].years.push(val[i].key[1]);
            vm.names[j].born.push(val[i].values[0]);
            vm.years.push(val[i].key[1]);
        }
        j++;
    });

JS Bin:

https://jsbin.com/qofuqatoqo/1/edit?html,js,console

修改

我的最终解决方案:

{
  "name": "loyalty-one-lois",
  "version": "1.0.0",
  "description": "Loyalty One LOIS",
  "keywords": [
    "Loyalty One",
    "LOIS",
    "BRMS"
  ],
  "author": "Loyalty One",
  "homepage": "https://www.loyalty.com/",
  "license": "MIT",
  "scripts": {
    "build:dev": "webpack --config config/webpack.dev.js --progress --profile",
    "build:docker": "npm run build:prod && docker build -t angular2-webpack-start:latest .",
    "build:prod": "webpack --config config/webpack.prod.js  --progress --profile --bail",
    "build": "npm run build:dev",
    "ci": "npm run lint && npm test && npm run e2e",
    "clean:dist": "npm run rimraf -- dist",
    "clean:install": "npm set progress=false && npm install",
    "clean:start": "npm start",
    "clean": "npm cache clean && npm run rimraf -- node_modules doc coverage dist",
    "docker": "docker",
    "docs": "npm run typedoc -- --options typedoc.json --exclude '**/*.spec.ts' ./src/",
    "e2e:live": "npm run e2e -- --elementExplorer",
    "e2e": "npm run protractor",
    "github-deploy:dev": "webpack --config config/webpack.github-deploy.js --progress --profile --github-dev",
    "github-deploy:prod": "webpack --config config/webpack.github-deploy.js --progress --profile --github-prod",
    "github-deploy": "npm run github-deploy:dev",
    "lint": "npm run tslint \"src/**/*.ts\"",
    "postversion": "git push && git push --tags",
    "prebuild:dev": "npm run clean:dist",
    "prebuild:prod": "npm run clean:dist",
    "preclean:install": "npm run clean",
    "preclean:start": "npm run clean",
    "pree2e": "npm run webdriver:update -- --standalone",
    "preversion": "npm test",
    "protractor": "protractor",
    "rimraf": "rimraf",
    "server:dev:hmr": "npm run server:dev -- --inline --hot",
    "server:dev": "webpack-dev-server --config config/webpack.dev.js --progress --profile --watch --content-base src/",
    "server:prod": "http-server dist --cors",
    "server": "npm run server:dev",
    "start:hmr": "npm run server:dev:hmr",
    "start": "npm run server:dev",
    "test": "karma start",
    "tslint": "tslint",
    "typedoc": "typedoc",
    "version": "npm run build",
    "watch:dev:hmr": "npm run watch:dev -- --hot",
    "watch:dev": "npm run build:dev -- --watch",
    "watch:prod": "npm run build:prod -- --watch",
    "watch:test": "npm run test -- --auto-watch --no-single-run",
    "watch": "npm run watch:dev",
    "webdriver-manager": "webdriver-manager",
    "webdriver:start": "npm run webdriver-manager start",
    "webdriver:update": "npm run webdriver-manager update",
    "webpack-dev-server": "webpack-dev-server",
    "webpack": "webpack"
  },
  "dependencies": {
    "@angular/common": "2.4.4",
    "@angular/compiler": "2.4.4",
    "@angular/core": "2.4.4",
    "@angular/forms": "2.4.4",
    "@angular/http": "2.4.4",
    "@angular/platform-browser": "2.4.4",
    "@angular/platform-browser-dynamic": "2.4.4",
    "@angular/platform-server": "2.4.4",
    "@angular/router": "3.4.4",
    "@angular2-material/core": "2.0.0-alpha.8-2",
    "@angular2-material/radio": "2.0.0-alpha.8-2",
    "@angularclass/conventions-loader": "^1.0.13",
    "@angularclass/hmr": "~1.2.2",
    "@angularclass/hmr-loader": "~3.0.2",
    "@angularclass/request-idle-callback": "^1.0.7",
    "@angularclass/webpack-toolkit": "^1.3.3",
    "assets-webpack-plugin": "^3.5.1",
    "core-js": "2.4.1",
    "http-server": "^0.9.0",
    "ie-shim": "^0.1.0",
    "moment": "^2.17.1",
    "mydatepicker": "1.3.0",
    "ng2-datepicker": "^1.4.8",
    "ng2-my-datepicker": "^0.1.1",
    "parse5": "^3.0.1",
    "primeng": "^2.0.0-rc.1",
    "primeui": "^4.1.15",
    "rxjs": "5.0.3",
    "zone.js": "0.7.6"
  },
  "devDependencies": {
    "@types/core-js": "^0.9.35",
    "@types/hammerjs": "^2.0.34",
    "@types/jasmine": "^2.5.41",
    "@types/node": "^7.0.3",
    "@types/protractor": "^4.0.0",
    "@types/selenium-webdriver": "2.53.39",
    "@types/source-map": "^0.5.0",
    "@types/uglify-js": "^2.6.28",
    "@types/webpack": "^2.2.3",
    "angular2-template-loader": "^0.6.0",
    "awesome-typescript-loader": "^3.0.0-beta.18",
    "codelyzer": "~2.0.0-beta.4",
    "copy-webpack-plugin": "^4.0.1",
    "css-loader": "^0.26.1",
    "exports-loader": "^0.6.3",
    "expose-loader": "^0.7.1",
    "file-loader": "^0.9.0",
    "gh-pages": "^0.12.0",
    "html-webpack-plugin": "^2.26.0",
    "imports-loader": "^0.7.0",
    "istanbul-instrumenter-loader": "^1.2.0",
    "json-loader": "^0.5.4",
    "karma": "^1.4.0",
    "karma-chrome-launcher": "^2.0.0 ",
    "karma-coverage": "^1.1.1",
    "karma-jasmine": "^1.1.0",
    "karma-mocha-reporter": "^2.2.2",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "2.0.1",
    "parse5": "^3.0.1",
    "protractor": "^5.0.0",
    "raw-loader": "0.5.1",
    "remap-istanbul": "^0.8.4",
    "rimraf": "^2.5.4",
    "source-map-loader": "^0.1.6",
    "string-replace-loader": "^1.0.5",
    "style-loader": "^0.13.1",
    "to-string-loader": "^1.1.5",
    "ts-helpers": "1.1.2",
    "ts-node": "^2.0.0",
    "tslint": "4.3.1",
    "tslint-loader": "^3.3.0",
    "typedoc": "^0.5.5",
    "typescript": "2.1.5",
    "url-loader": "^0.5.7",
    "webpack": "1.14.0",
    "webpack-dev-middleware": "1.9.0",
    "webpack-dev-server": "1.16.2",
    "webpack-md5-hash": "0.0.5",
    "webpack-merge": "2.4.0"
  },
  "repository": {
    "type": "",
    "url": ""
  },
  "bugs": {
    "url": ""
  },
  "engines": {
    "node": ">= 4.2.1",
    "npm": ">= 3"
  }
}

2 个答案:

答案 0 :(得分:1)

我的解决方案,使用对象作为字典来存储密钥, 然后将该字典转换为所需的数组。

var input={
    "people": [{
        "key": ["2Anita", "1916"],
        "values": ["11"]
    }, {
        "key": ["2Anita", "1917"],
        "values": ["20"]
    },  {
        "key": ["2Anna", "1916"],
        "values": ["153"]
    }, {
        "key": ["2Anna", "1917"],
        "values": ["91"]
    }]
}

var inputArray = input.people;

var dictionary = {}
inputArray.forEach(function(v){
  if(dictionary[v.key[0]]==null)
  {
    dictionary[v.key[0]] = {
      years:[parseInt(v.key[1])],
      born:[ parseInt(v.values[0])]
    }
  } else {
    dictionary[v.key[0]].years.push(parseInt(v.key[1]));
    dictionary[v.key[0]].born.push(parseInt(v.values[0]));
  }
});

var final = [];

for (var key in dictionary)
{
  final.push({
   name: key,
   years:dictionary[key].years,
   born:dictionary[key].born
  });
}

答案 1 :(得分:1)

这是我的方法

let data = {
    "people": [{
        "key": ["2Anita", "1916"],
        "values": ["11"]
    }, {
        "key": ["2Anita", "1917"],
        "values": ["20"]
    },  {
        "key": ["2Anna", "1916"],
        "values": ["153"]
    }, {
        "key": ["2Anna", "1917"],
        "values": ["91"]
    }]
}

let auxNames = data.people.reduce((initial, item) => {

  if (!initial.hasOwnProperty(item.key[0])) {
          initial[item.key[0]] = {
      years: [],
      born: []
    }  
  }

  initial[item.key[0]].years.push(item.key[1])
  initial[item.key[0]].born.push(item.values[0])

    return initial
}, {})

const names = []

for (let prop in auxNames) {
    names.push({
    name: prop,
    years: auxNames[prop].years,
    born: auxNames[prop].born
  })
}