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
alice_morgan
1711 silver badge10 bronze badges
3 Answers 3
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
Kinglish
23.7k4 gold badges25 silver badges43 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
Kinglish
You haven't initialized the arrays you're trying to
push on, so it's erroring out.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
Mr. Polywhirl
49.1k12 gold badges96 silver badges147 bronze badges
Comments
lang-js