I have an object as follows
{
"s": "success",
"result": {
"XX-YY-12-33": {
"quantity": "88",
"warehouse_name": "USA Hub"
},
"AD-12-Y6-00": {
"quantity": "99",
"warehouse_name": "USA Hub"
}
}
}
The result object contains multiple objects which actually is the id of an sku
I want to access this each sku but don't have them separately anywhere. Can anyone tell how can I access them?
You mean this?
Object.entries and reduce
Had you been clearer, I would have given a more complex answer first time around
const obj = {
"s": "success",
"result": {
"XX-YY-12-33": {
"quantity": "88",
"warehouse_name": "USA Hub"
},
"AD-12-Y6-00": {
"quantity": "99",
"warehouse_name": "USA Hub"
}
}
}
const res = Object.entries(obj.result)
.reduce((acc, [key,{quantity}]) => { // spread the key and extracted quantity from value
acc.keys.push(key); // save the key
acc.quantity.push(+quantity); // save the quantity (unary plus to convert to number)
acc.sum += +quantity; // sum it
return acc;
},{keys:[],quantity:[],sum:0}); // into an initialised object
console.log(res)
Does this help?
I've put some comments in the code for further explanation.
const data = {
"XX-YY-12-33": {
"quantity": "88",
"warehouse_name": "USA Hub"
},
"AD-12-Y6-00": {
"quantity": "99",
"warehouse_name": "USA Hub"
}
};
// You can extract only the ids using Object.keys
const dataIds = Object.keys(data);
// Having the ref of the ids you can now iterate over them to extract the info you need per id
// Using array map function for example we can extract all the quantities:
const dataQtys = dataIds.map((id) => Number(data[id].quantity));
// alternatively you can use "Object.entries".
// If you want to sum all quantities you can use array reduce function:
const sum = dataQtys.reduce((res, qty) => res + qty, 0);
console.log('Ids: ', dataIds);
console.log('Quantities: ', dataQtys);
console.log('Sum: ' + sum);