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
 }, {})
asked May 24, 2021 at 19:44

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)

answered May 24, 2021 at 19:50
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);

answered May 24, 2021 at 19:52

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; }

answered May 24, 2021 at 20:08

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.