I am having an object that has the following structure
const arr = [
{field: "f1", values: [{ count:1, value: "a"}, { count:2, value: "b"}] },
{field: "f2", values: [{ count:3, value: "c"}, { count:4, value: "d"}] }
];
Output should look like
output = {
f1: { name: "f1", selected: [] },
f2: { name: "f2", selected: [] }
}
Basically the value in field
should be key in the new object, also its name should have the same value with empty selected array
Code that I tried.
arr.map(item => {
return {
item: {name: item, selected: []
}
);
CodePudding user response:
const arr = [
{ field: "f1", values: [{ count: 1, value: "a" }, { count: 2, value: "b" }] },
{ field: "f2", values: [{ count: 3, value: "c" }, { count: 4, value: "d" }] }
]
const output = arr.reduce((p, { field }) => {
p[field] = { name: field, selected: [] };
return p;
}, {});
console.log(output);
CodePudding user response:
We can use Array.reduce()
to do it
let arr = [
{ field: "f1", values: [{ count: 1, value: "a" }, { count: 2, value: "b" }] },
{ field: "f2", values: [{ count: 3, value: "c" }, { count: 4, value: "d" }] }
]
let result = arr.reduce((a,v) => {
let obj = {'name':v.field, 'selected': []}
a[v.field] = obj
return a
},{})
console.log(result)
CodePudding user response:
Reduce saves an assignment but makes the code more complex to read.
forEach is better in this case
const arr = [
{field: "f1", values: [{ count:1, value: "a"}, { count:2, value: "b"}]},
{field: "f2", values: [{ count:3, value: "c"}, { count:4, value: "d"}]}
];
const obj = {};
arr.forEach(({field}) => obj[field] = {name:field, selected:[]})
console.log(obj)
CodePudding user response:
You can use a .map()
to get the field name, and a .reduce()
to compose the object from the field name:
const input = [
{field: "f1", values: [{ count:1, value: "a"}, { count:2, value: "b"}] },
{field: "f2", values: [{ count:3, value: "c"}, { count:4, value: "d"}] }
];
let result = input.map(obj => obj.field).reduce((acc, name) => {
acc[name] = { name: name, selected: [] };
return acc;
}, {});
console.log(result);
CodePudding user response:
All the other answers seem to be using reduce. Here's another way without it:
let arr = [
{field: "f1", values: [{ count:1, value: "a"}, { count:2, value: "b"}]},
{field: "f2", values: [{ count:3, value: "c"}, { count:4, value: "d"}]}
];
let newobj = {};
arr.forEach((obj) => {
newobj[obj.field] = { name: obj.field, selected: [] }
});