I am building an app and I have an array of objects. The objects have a key where the value is an array of objects with key value pairs. I would like to convert this array into an array of just objects
My first array looks like this:
const firstArray = [
{
amount: 343,
code: "RCU8YI0NKS",
items: [
{
productOne: "crust",
quantity: 2.2,
},
{
productTwo: "dust",
quantity: 34,
},
],
user_id: "wewewefwOHG22323kj",
},
{
amount: 343,
code: "RCU8YI0NKS",
items: [
{
productTwo: "dust",
quantity: 32,
},
{
productThree: "must",
quantity: 34,
},
],
user_id: "m2LgLRD9MEVNAX56JTpRYDkOOjd2",
},
];
I would like it to look like this array:
const secondArray = [
{
amount: 343,
code: "RCU8YI0NKS",
crust: 2.2,
dust: 34,
user_id: "wewewefwOHG22323kj",
},
{
amount: 343,
code: "RCU8YI0NKS",
dust: 32,
must: 34,
user_id: "m2LgLRD9MEVNAX56JTpRYDkOOjd2",
},
];
If anyone knows how to do this, please help.
Thanks.
2
Answers
I can’t see other way to do it without scanning all arrays, except if there’s a kind of pattern I didn’t see in the data.
The reduce function should do the job :
Looks like you just have to turn the
items
into key value pairs and add them to the object: