I am trying to create multiple arrays of objects with each keys inside the object.
How can I generate my expected output (shown below the initial array)?
Initial array:
[{
title: 'Linus tech tips',
name: 'Linus',
id: 'SA946',
},
{
title: 'Linus tech tips',
name: 'Colton',
id: 'SA947',
}
];
Expected output:
[{
text: 'Linus tech tips',
}, {
text: 'Linus',
}, {
text: 'SA946',
}, ],
[{
text: 'Linus tech tips',
}, {
text: 'Colton',
}, {
text: 'SA947',
}, ],
CodePudding user response:
You need to iterate over the keys, then flatten the array.
[{
title: 'Linus tech tips',
name: 'Linus',
id: 'SA946',
},
{
title: 'Linus tech tips',
name: 'Colton',
id: 'SA947',
}].map(
item => {
return Object.keys(item).map(
key => {
return {text: item[key]}
}
)
}
).flat()
[
{
"text": "Linus tech tips"
},
{
"text": "Linus"
},
{
"text": "SA946"
},
{
"text": "Linus tech tips"
},
{
"text": "Colton"
},
{
"text": "SA947"
}
]
Or, if you want to have the items separated, do not use flat()
at the end:
[
[
{
"text": "Linus tech tips"
},
{
"text": "Linus"
},
{
"text": "SA946"
}
],
[
{
"text": "Linus tech tips"
},
{
"text": "Colton"
},
{
"text": "SA947"
}
]
]
CodePudding user response:
You can use array.map
to achieve that. Please have a look:
const initial = [
{
title: 'Linus tech tips',
name: 'Linus',
id: 'SA946',
},
{
title: 'Linus tech tips',
name: 'Colton',
id: 'SA947',
},
];
const expected = initial.map(
(item) => Object.values(item).map(
(itemValue) => ({ text: itemValue }),
),
);
console.log(expected);