简体   繁体   English

将嵌套数组转换为具有键值的单个对象 Javascipt

[英]convert nested array to single object with key values Javascirpt

I have an array that contains nested arrays.我有一个包含嵌套数组的数组。

The nested array can contain multiple objects.嵌套数组可以包含多个对象。

const axisChoiceLoop = _.map(groupByAxisChoice) 

output:输出:

[
 0: [ {age: 15, count: 242, role: "JW"}] // length 1
 1: [ {age: 21, count: 995, role: "JW"} , {age: 21, count: 137, role: "SW"} ] // length 2
 2: [ {age: 25, count: 924, role: "JW"},  {age: 25, count: 455, role: "SW"}, {age: 25, count: 32, role: "EW"} ]
]

I would like the nested arrays to be single objects, using their role as the key, and count as the value我希望嵌套数组是单个对象,使用它们的角色作为键,并算作值

expected output would look like this预期输出看起来像这样

[ 
  {age :15, JW: 242}, 
  {age: 21, JW:995, SW: 137},
  {age: 25, JW: 924, SW: 445, EW: 32}
]

Edit: I have tried the following code编辑:我尝试了以下代码

const result = groupByAxisChoice.reduce(
    (obj, item) => Object.assign(obj, { [item.role]: item.count }),
    {},
  )

Which outputs: { undefined: undefined }哪些输出: { undefined: undefined }

Figured it out...弄清楚了...

const result = groupByAxisChoice.map(items =>
    items.reduce((obj, item) => Object.assign(obj, { age: item.age, [item.role]: item.count }), {}),
)

This is what I ended up with, I know it's not optimized:这就是我的结果,我知道它没有优化:

var arr = [
 [ {age: 15, count: 242, role: "JW"}], // length 1
 [ {age: 21, count: 995, role: "JW"} , {age: 21, count: 137, role: "SW"} ], // length 2
 [ {age: 25, count: 924, role: "JW"},  {age: 25, count: 455, role: "SW"}, {age: 25, count: 32, role: "EW"} ]
];
var newArr = [];
arr.forEach(function(a) {
    var ob = {age: a[0].age};
    a.forEach(d => ob[d.role] = d.count); 
    newArr.push(ob);
});

I'll try to make it better (i don't know how to use underscore.js)...我会努力让它变得更好(我不知道如何使用underscore.js)...

another solutions另一种解决方案

const b = a.map(item => {
return item.reduce((arr,curr) => {
    return {
      ...arr,
      ['age']: curr['age'],
      [curr['role']]: curr['count'],
    }
  }, {})
})
console.log(b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM