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.
Looks like you just have to turn the items
into key value pairs and add them to the object:
const flatten = arr => arr.map(({items, ...obj}) => items.reduce((agg, {quantity, ...rest}) => (agg[Object.values(rest)[0]] = quantity, agg), obj))
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",
},
];
console.log(flatten(firstArray))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments