I have the following array with nested arrays:
const options = [
[
{
label: "Blue",
option_id: "1"
},
{
label: "Small",
option_id: "2"
}
],
[
{
label: "Red",
option_id: "1"
},
{
label: "Large",
option_id: "2"
}
]
];
I want to create an array of objects from each pair, ex:
[
{
label: ”Blue Small“,
option_id: [1,2]
},
...
]
edit: thanks everyone for the great answers
Use .map
over the options
array, and reduce
each subarray into an object:
const options = [
[
{
label: "Blue",
option_id: "1"
},
{
label: "Small",
option_id: "2"
}
],
[
{
label: "Red",
option_id: "1"
},
{
label: "Large",
option_id: "2"
}
]
];
const result = options.map(arr =>
arr.reduce(
(a, { label, option_id }) => {
a.label += (a.label ? ' ' : '') + label;
a.option_id.push(option_id);
return a;
},
{ label: '', option_id: [] }
)
);
console.log(result);
reduce is a great way to these array transformations.
const options = [
[
{
label: "Blue",
option_id: "1"
},
{
label: "Small",
option_id: "2"
}
],
[
{
label: "Red",
option_id: "1"
},
{
label: "Large",
option_id: "2"
}
]
];
const newArray = options.reduce((prev,current)=>{
const label = current.map(o=>o.label).join(' ')
const optionid = current.map(o=>o.option_id)
return [...prev,{option_id:optionid,label}]
},[])
console.log(newArray)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With