1

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 ?

jabaa
  • 5,844
  • 3
  • 9
  • 30
skyniazi
  • 29
  • 4

3 Answers3

0

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);
      }
    }
  }
}
alonealgorithm
  • 149
  • 1
  • 1
  • 5
  • but this is restricted to two array properties ,array properties can varry depending on the result e.g this is real json output "sublists": { "item": [ { "line": "1", "amount": "1200.00", "id": "227", "item": "227", "item_display": "5800520002800", "quantity": "1" } ] } , i want it to be access dynamically , in this case output will be data , line , 1 – skyniazi Mar 11 '22 at 01:16
  • I've adjusted my answer. Let me know if you need any additional modifications or clarification. – alonealgorithm Mar 11 '22 at 01:53
0

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) ;


Array name: data. Key1: a. Value: 2
Array name: data. Key1: b. Value: 4
Array name: memo. Key1: a. Value: 5
0stone0
  • 34,288
  • 4
  • 39
  • 64
0

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");

Serge
  • 40,935
  • 4
  • 18
  • 45
  • this is i was trying to do , thank you very much @Serge , this second solution is dynamic and working perfect – skyniazi Mar 11 '22 at 10:26
  • Hi Serge , how i can access object within an array , its a same json as showing above but one more array is added into the item array e.g { "item": [ { "line": "1", "amount": "1700.00", "id": "227", "item": "227", "address": { "zip":"4001" , "country": "US" }, "tran_date": "01/01/2022", "quantity": "1" } ] } – skyniazi Mar 15 '22 at 14:41
  • @skyniazi I updated my answer. This code should be working for both – Serge Mar 15 '22 at 23:51