0

I want to change this

const a = [{
        id: 1,
        name: 'a'
      }, {
        id: 2,
        name: 'b'
      }]

to

{
        id: [1,2],
        name: [a, b]
      }

I'm stuck at how to push the id and name into the object

 arr.reduce((accum, val) => {
    let accum = {
      id: val.id,
      name: val.name
    }
    accum.id.push(val.id) //it doesn't work like this
    return accum
  }, {})

3 Answers 3

1

You were just missing the proper initial accum value, which would contain the arrays you want.

const a = [{
  id: 1,
  name: 'a'
}, {
  id: 2,
  name: 'b'
}]


let arr = a.reduce((accum, val) => {
  accum.id.push(val.id);
  accum.name.push(val.name);
  return accum
}, {
  id: [],
  name: []
})
console.log(arr)

Sign up to request clarification or add additional context in comments.

Comments

0

const a = [{
        id: 1,
        name: 'a'
      }, {
        id: 2,
        name: 'b'
      }]
 const newObj = {};
 
a.forEach(ele => {
  const {id, name} = ele;
  newObj.id.push(id);
  newObj.name.push(name);
})

console.log(newObj);

1 Comment

You haven't initialized the arrays you're trying to push on, so it's erroring out.
0

If you want to build a list of values for each key, you could reduce every item; and for each item, reduce their key-value pairs.

In the example below, the keyValues function is decoupled from the sample data.

const keyValues = (...items) =>
  items.reduce((accOut, item) =>
    Object.entries(item).reduce((accIn, [key, value]) =>
      ({ ...accIn, [key]: [...(accIn[key] || []), value] }), accOut), {})

const data = [
  { id: 1, name: 'a' },
  { id: 2, name: 'b' }
];

console.log(keyValues(...data));
.as-console-wrapper { top: 0; max-height: 100% !important; }

Alternatively, you could zip the data and then bin it.

const zip = (...arr) => arr[0].map((_, c) => arr.map(row => row[c]))

const bin = (...arr) =>
  zip(...arr.map(Object.entries)).reduce((acc, ...values) =>
    ({ ...acc, [values[0][0][0]]: values[0].map(([key, value]) => value) }), {})

const data = [
  { id: 1, name: 'a' },
  { id: 2, name: 'b' }
];

console.log(bin(...data));
.as-console-wrapper { top: 0; max-height: 100% !important; }

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.