I have a nested array which has property called "options". The options property is an array of objects, and now each object has it's own property fields, which is also an array of objects.
So from every option in options array I need to get the option fields, and place them all in one new array.
I will post an image how my array looks like as it might be easier to understand how it looks. Here is the array image.
Now I have tried mapping through them all and then getting the fields but in my way it returns the array but with every fields object, but I want it to be returned as each field inside fields should be a new array property.
const obj = {
key: 'clothes',
label: 'Clothes',
options: [
{
key: 'base-layers',
label: 'base-layers',
fields: [{ key: 'brand', label: 'brand' }, { key: 'size', label: 'Size' }],
},
{
key: 'front-layers',
label: 'front-layers',
fields: [{ key: 'gender', label: 'Gender' }, { key: 'condition', label: 'Condition' }],
},
],
};
const getFields = obj.options.map(a => a.map(f => f.fields));
const final = getFields.reduce((r, c) => Object.assign(r, c), {}));
So each field inside fields object should be it's own property in new array of objects.
I would really appriciate the help!
CodePudding user response:
You can use a single reduce function to iterate over each option and combine the fields collection.
const obj = {
key: 'clothes',
label: 'Clothes',
options: [
{
key: 'base-layers',
label: 'base-layers',
fields: [{ key: 'brand', label: 'brand' }, { key: 'size', label: 'Size' }, { key: 'condition', label: 'Condition' }],
},
{
key: 'front-layers',
label: 'front-layers',
fields: [{ key: 'gender', label: 'Gender' }, { key: 'condition', label: 'Condition' }],
},
],
};
const allFields = obj.options.reduce((fields, option) => [...fields, ...option.fields], []);
console.log(allFields);
// Combine all fields without duplications (not optimized)
const allFieldsUnique = obj.options.reduce((fields, option) => {
return [...fields, ...option.fields.filter(a => !fields.some(b => b.key === a.key))];
}, []);
console.log(allFieldsUnique);
CodePudding user response:
Use Array.flatMap()
to get an array by plucking the fields from each option.
If you want an object, map the fields to an array of [key, value]
pairs, and convert to an object with Object.fromEntries()
:
const obj = {"key":"clothes","label":"Clothes","options":[{"key":"base-layers","label":"base-layers","fields":[{"key":"brand","label":"Brand"},{"key":"size","label":"Size"}]},{"key":"front-layers","label":"front-layers","fields":[{"key":"gender","label":"Gender"},{"key":"condition","label":"Condition"}]}]};
const arr = obj.options.flatMap(option => option.fields)
console.log(arr);
const object = Object.fromEntries(obj.options.flatMap(option =>
option.fields.map(({ key, label }) => [key, label])
));
console.log(object);