I need to restructure the JSON object with existing key values, please check below input format of JSON
{
'Demo-1': [
{
sku: 'Brisk',
count: '2',
},
{
sku: 'Pepsi Cans',
count: '2',
},
{
sku: 'Pepsi Cans',
count: '4',
}
],
'Demo-2' :{
"A":[
{
sku: 'Mountain',
count: '4',
},
{
sku: 'Pepsi Bottles',
count: '4',
}
],
"B":[
{
sku: 'Lipton Dietgreentea',
count: '2',
},
{
sku: 'Lipton Dietgreentea Mixedberry',
count: '2',
}
]
}
}
In the above input JSON, the "Demo-1" have a single array of object and the second one has two array object. I would like to change the above array, into like below Result
{
'Demo-1': {
items: [{
sku: 'Brisk',
count: '2',
},
{
sku: 'Pepsi',
count: '2',
},
{
sku: 'Pepsi',
count: '4',
}
],
mode: "Veri",
istatus: "open"
},
'Demo-2': {
"items":{
"A" :[
{
sku: 'Mountain',
count: '4',
},
{
sku: 'Pepsi Bottles',
count: '4',
}
],
"B" :[
{
sku: 'Lipton Dietgreentea',
count: '2',
},
{
sku: 'Lipton Dietgreentea Mixedberry',
count: '2',
}]
},
mode: "Doubled",
istatus: "Closed"
}
}
I already using below code solution for partially achiving this
Object.fromEntries(
Object.entries(obj).map(
([key, items]) => [key, { items, mode: "verification", status: "open" }]
)
)
Now if the object has two array objects like Demo-2, the mode value should be "Doubled" please help me out in resolving this.
Thanks in advance.
You need to add condition into your mapping function.
Proper condition depends on what possible items
values may be.
If items
always either array
or { A, B } object
, following condition is enough:
Object.fromEntries(
Object.entries(obj).map(
([key, items]) => [key, { items, mode: Array.isArray(items) ? 'Single' : 'Doubled', status: 'open' }]
)
)