Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

179
Vistas
Getting the array name and values in Javacript Object

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 ?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

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


  • The first if statement if to check if the varaible is an array or object. Logic taken from:
    How do you check if a variable is an array in JavaScript?

Array name: data. Key1: a. Value: 2
Array name: data. Key1: b. Value: 4
Array name: memo. Key1: a. Value: 5
about 4 years ago · Juan Pablo Isaza Denunciar

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

about 4 years ago · Juan Pablo Isaza Denunciar

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);
      }
    }
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda