Please help me to recreate the JSON object received from API, refer below JSON object from API below is Input JSON
{
'Demo-1': [
{
sku: 'Brisk',
count: '2',
},
{
sku: 'Pepsi Cans',
count: '2',
},
{
sku: 'Pepsi Cans',
count: '4',
}
],
'Demo-2' : [
{
sku: 'Mountain',
count: '4',
},
{
sku: 'Pepsi Bottles',
count: '4',
},
{
sku: 'Lipton Dietgreentea',
count: '2',
},
{
sku: 'Lipton Dietgreentea Mixedberry',
count: '2',
}
]
}
from this to convert below JSON object with additional keys, and restructure the array items inside the another key
Result should be like
{
'Demo-1': {
items: [{
sku: 'Brisk',
count: '2',
},
{
sku: 'Pepsi',
count: '2',
},
{
sku: 'Pepsi',
count: '4',
}
],
mode: "Veri",
status: "open"
},
'Demo-2': {
"items": [{
sku: 'Mountain',
count: '4',
},
{
sku: 'Pepsi Bottles',
count: '4',
},
{
sku: 'Lipton Dietgreentea',
count: '2',
},
{
sku: 'Lipton Dietgreentea Mixedberry',
count: '2',
}
],
mode: "Clear",
status: "Closed"
}
}
I tried in angular but I cant achieve the result, please look out the code below
Object.entries(_data).map((items,idx)=>{
this._newPickLists = {
items[0] :{
items : items[1],
mode : 'Verification',
status : 'open'
}
}
})
Thanks in Advance
CodePudding user response:
Using Object.entries
and Object.fromEntries
, you can just change the value to the object with items as the key
const obj = {"Demo-1":[{"sku":"Brisk","count":"2"},{"sku":"Pepsi Cans","count":"2"},{"sku":"Pepsi Cans","count":"4"}],"Demo-2":[{"sku":"Mountain","count":"4"},{"sku":"Pepsi Bottles","count":"4"},{"sku":"Lipton Dietgreentea","count":"2"},{"sku":"Lipton Dietgreentea Mixedberry","count":"2"}]};
console.log(
Object.fromEntries(
Object.entries(obj).map(
([key, items]) => [key, { items, mode: "verification", status: "open" }]
)
)
)
CodePudding user response:
Just replace the newObject
with the variable in your app.
const newObject = {};
for (const [key, value] of Object.entries(obj)) {
newObject[key] = {};
newObject[key]["items"] = value;
newObject[key].mode = "Clear";
newObject[key].status = "Closed";
}
console.log(newObject);
CodePudding user response:
Here is a solution that will update the original data object:
Object.keys(data).forEach((key)=> {
data[key] = {items: data[key], mode: 'Veri', status: 'open' }}
)