Reputation: 171
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
}, {})
Upvotes: 0
Views: 63
Reputation: 48600
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; }
Upvotes: 0
Reputation: 23654
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)
Upvotes: 1
Reputation: 61
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);
Upvotes: 0