Getting the array name and values in Javacript Object

Hello everyone ,
My JSON output is similar to this below object and we have an array values as showing below

I am trying to get the name of arrays and values in separate variable 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 output  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 
Array name :item, item: , 227
Array name :item, quantity: , 1 
Array name :shipping, line: , 1  and so on

Arrays properties can varry depending on the json ouput , im looking for a dynamic script in which i could access the array name and properties

here is my code , i can get the properties and values with this but unable to get the name of array in the output as mentioned above.

  jv = jsonData.sublists ;

function printValues(obj) {

        for(var k in obj) {

        //    console.log(k+obj[k]);

       

            if(obj[k] instanceof Object) {

                printValues(obj[k]);

            } else {

                console.log(k+''+obj[k] );

            };

        }

    };
 printValues(jv)

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

I don’t understand the output you are trying to get, but I would suggest you look at some of the methods on Object (like .values(), .keys(), and .entries()).


Object.keys(object1).forEach((key) => {
  Object.entries(object1[key]).forEach(([key, value]) => {
    console.log(key);
    console.log(typeof key);
    console.log(value);
    console.log(Array.isArray(value));
  });
});

start simple once u know how it works u can start doing loops

const data = object1.sublists

const {item, shipping} = data

const Array1 = [ `line: , ${item[0].line}` ]
const Array2 = [ `amount: , ${item[0].amount}` ]
console.log(Array1, Array2 )

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.