简体   繁体   中英

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 }

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)...

another solutions

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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