I am trying to manipulate an array of objects. It's a big tree as you u can see below.
I want to get both key value of la
and ld
at the zero index of the products
array and put them beside c
(in the dop
array).
Please find my codepen link in comments not sure why I am unable to share code pen link here
const arr = [
{
a: 1,
dop: [
{
c: 3,
//la: 11,
//ld: 33
products: [
{ ld: 11, la: 33 }, // <--- zero index
{ ld: 233, la: 44 } // <--
]
},
{ d: 4, e: 4 }
]
},
{
a: 1,
dop: [
{
c: 3,
//la: 11,
//ld: 33
products: [
{ ld: 11, la: 33 },
{ ld: 233, la: 44 }
]
},
{ d: 4, e: 4 }
]
}
];
CodePudding user response:
move or copy?
Here I copy
const arr = [{ a: 1, dop: [{ c: 3, products: [{ ld: 11, la: 33 }, { ld: 233, la: 44 } ] }, { d: 4, e: 4 } ] }, { a: 1, dop: [{ c: 3, products: [{ ld: 11, la: 33 }, { ld: 233, la: 44 } ] }, { d: 4, e: 4 } ] } ];
arr.forEach(item => Object.assign(item.dop[0],item.dop[0].products[0]))
console.log(arr)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Using map
and destructuring
const process = (data) =>
data.map(({ dop, ...rest }) => {
return {
...rest,
dop: dop.map(({ products, ...dopRest }) => {
const [{ ld, la }] = products ?? [{}];
return {
...dopRest,
ld,
la,
products,
};
}),
};
});
const arr = [
{
a: 1,
dop: [
{
c: 3,
//la: 11,
//ld: 33
products: [
{ ld: 11111, la: 11111 }, // <--- zero index
{ ld: 233, la: 44 },
{ ld: 233, la: 44 },
{ ld: 233, la: 44 },
],
},
{ d: 4, e: 4 },
],
},
{
a: 2,
dop: [
{
c: 3,
//la: 11,
//ld: 33
products: [
{ ld: 222222, la: 222222 }, // <--- zero index
{ ld: 233, la: 44 }, // <--
],
},
{ d: 4, e: 4 },
],
},
{
a: 2,
dop: [
{
c: 3,
//la: 11,
//ld: 33
products: [
{ ld: 333333, la: 3333333 }, // <--- zero index
{ ld: 233, la: 44 }, // <--
],
},
{ d: 4, e: 4 },
],
},
];
console.log(process(arr));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>