0

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 }

2
  • What code have you tried yourself? Commented Mar 20, 2020 at 1:38
  • @jfriend00 I have edited in my attempt at solving the problem Commented Mar 20, 2020 at 1:46

3 Answers 3

1

Figured it out...

const result = groupByAxisChoice.map(items =>
    items.reduce((obj, item) => Object.assign(obj, { age: item.age, [item.role]: item.count }), {}),
)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

another solutions

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.