I have a set of data that I wanted to create an object from, everything works well except that the inner nested object has 3 elements but only the last element is being printed. Below is my object structure
[
{
"item_id": 696136507565,
"seller_id": 2549116888,
"sku": [
{
"cart_id": 131,
"sku_id": 4939047817461,
},
{
"cart_id": 131,
"sku_id": 4939047817463,
},
{
"cart_id": 131,
"sku_id": 4939047817466,
}
],
},
{
"item_id": 729563966440,
"seller_id": 2211628865398,
"sku": [
{
"cart_id": 132,
"sku_id": 894758674833,
},
{
"cart_id": 132,
"sku_id": 4939047387945,
},
{
"cart_id": 132,
"sku_id": 1243567817466,
}
],
},
]
I needed to create an object of the below structure
checkList:{
seller_id:{
seller_id: boolean,
item_id:{
sku_id: boolean,
sku_id: boolean,
sku_id: boolean,
},
item_id:{
sku_id: boolean,
sku_id: boolean,
sku_id: boolean,
},
},
}
so my expected result from my new object will look like below:
{
"2549116888": {
"2549116888": false,
"696136507565": {
"696136507565": false,
//sku
"4939047817461": false,
"4939047817463": false,
"4939047817466": false,
}
},
"2211628865398": {
"2211628865398": false,
"729563966440": {
"729563966440": false,
//sku
"894758674833": false,
"4939047387945": false,
"1243567817466": false,
}
},
}
but this below is what I was able to come up with, only the last element of each sku is printed and the others are not printed:
{
"2549116888": {
"2549116888": false,
"696136507565": {
"696136507565": false,
//sku
"4939047817466": false,
}
},
"2211628865398": {
"2211628865398": false,
"729563966440": {
"729563966440": false,
//sku
"1243567817466": false,
}
},
}
Below is the code that I have tried so far
let myNewObj = {}
myObj?.map((value) =>{
value?.sku?.map((val,key) =>{
let skuObj = {
...skuObj,
[val.sku_id]: false
}
myNewObj ={...myNewObj,
[value.seller_id]:{
[value.seller_id]: false,
[value.item_id]:{
[value.item_id]: false,
[val.sku_id]: false,
},
},
}
})
})
}
How can I modify my code to get the result I wanted and print all the sku with boolean values. Thanks in advance
3
Answers
You could map new entries for objects.
You can try this
reduce
approachThe issue with your current code is that it’s overwriting the
myNewObj
andskuObj
objects in each iteration of the map function. This means that only the lastsku_id
anditem_id
for eachseller_id
are being stored inmyNewObj
.I have changed the code to help you acheive that, here is the updated code: