My JSON output is similar to this below object and we have an array values as showing below
const object1 = {
"sublists": {
"item": [{
"line": "1",
"amount": "1200.00",
"id": "227",
"item": "227",
"item_display": "5800520002800",
"quantity": "1"
}
],
"shipping": [{
"line": "1",
"amount": "1200.00",
"id": "227",
"quantity": "1"
}
]
}
}
I am trying to get the name of arrays and values in separate variable as showing below
Array name :item, line: , 1 Array name :item , amount : 1200 Array name :item, id : 227 and so on ... the array properties can varry depending on the json ouput , im looking for a dynamic script in which i could access the array name and properties
Can someone help me on this ?
The easy way to achieve the desired outcome is to pass the 'parentKey' to the recursive call:
const object1 = {sublists: {sales_order: [], data: [{"key1": "a", "value": 2 }, {"key1": "b", "value": 4 }], memo: [{"key1": "a", "value": 5 }] } };
function printValues(obj, parentName = null) {
if (Object.prototype.toString.call(obj) === '[object Array]') {
obj.forEach(o => console.log(`Array name: ${parentName}. Key1: ${o.key1}. Value: ${o.value}`));
} else {
for (let k in obj) {
printValues(obj[k], k);
}
}
};
printValues(object1) ;
if statement if to check if the varaible is an array or object. Logic taken from:Array name: data. Key1: a. Value: 2
Array name: data. Key1: b. Value: 4
Array name: memo. Key1: a. Value: 5
try this
function iterateObject(obj, parent) {
if (typeof obj == "object")
if (!Array.isArray(obj))
Object.keys(obj).forEach((prop) => {
if (typeof obj[prop] == "object") iterateObject(obj[prop], prop);
else console.log(`Parent name : ${parent}, ${prop} : ${obj[prop]}`);
});
else
obj.forEach((elem) => {
iterateObject(elem, parent);
});
else console.log(`Parent name : ${parent}, ${parent} : ${obj}`);
}
iterateObject(object1,"sublists");
UPDATE
this is code for your json in comment
iterateObject(object01,"item");
I believe this will solve your problem. I followed the recursive nature of the code you gave and adapted it to make sure it was giving the output you desired. If you have any questions please let me know, and I'll try to address them.
function printValues(obj) {
for (const [objKey, objValue] of Object.entries(
obj
)) {
if (
typeof objValue === 'object' &&
!objValue.length
) {
printValues(objValue);
} else if (
objValue !== undefined &&
objValue.length > 0
) {
for (let i = 0; i < objValue.length; i++) {
const currentObject = objValue[i];
let str = '';
for (const [key, value] of Object.entries(
currentObject
)) {
str += `Array name: ${objKey} , key1: ${key} , value: ${value}\n`;
}
console.log(str);
}
}
}
}