0

I have this code, but it doesn't prints subkeys....

    for (var key in result) {
        if (!result.hasOwnProperty(key)) continue;
        var obj = result[key];
        for (var prop in obj) {
            if (!obj.hasOwnProperty(prop)) continue;
            alert(prop + " = " + obj[prop]);
        }
    }

When is an object print: someKey[Object object]

my result (example):

[ { "branch_id": 992, "sale_id": 24422, "identifier": "", "emitter": { "id": 68, "tax_id": "", "address": { "street": "Carretera a buenavista km 21", "country_code": "MEX", } } } ]

Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
N. Tobías
  • 55
  • 1
  • 12

3 Answers3

1

It's better if you handle your function as recursive function instead nested for in statements, so you only need to verify if your value if an object to recall the function again, so in code you have this:

var json = {
 "key1": "value1",
 "key2": "value2",
 "key3": {
   "sub_1_key1": "subvalue1",
    "sub_1_key2": "subvalue2",
    "sub_1_key3": "subvalue3",
    "sub_1_key4": {
     "sub_2_key1": "sub_2_value1"
    }
  },
};

var logger = document.getElementById('logs');

function goThroughJSON(json) {
 for (var attr in json) {
   var value = json[attr];
   if (typeof value === 'object' && !(attr instanceof Array)) {
     return goThroughJSON(value);
    }
    logger.innerHTML += attr + '<br>'
  }
}

goThroughJSON(json);
<div id="logs"></div>

I really hope you find it helful.

Juorder Gonzalez
  • 1,642
  • 1
  • 8
  • 10
0

You can use a recursive approach. For any key, if it contains an object value, you can once again call the same function again.

const data = [{ "branch_id": 992, "sale_id": 24422, "identifier": "", "emitter": { "id": 68, "tax_id": "", "address": { "street": "Carretera a buenavista km 21", "country_code": "MEX", } } } ];

const ObjectKey = o => {
  Object.keys(o).forEach(k => {
    if(typeof o[k] === 'object'){
      ObjectKey(o[k]);
    } else {
      console.log(k, " ", o[k]);
    }
  });
}

data.forEach(o => {
  ObjectKey(o);
});
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

I found the answer here.

Get all keys of a deep object in Javascript

function getDeepKeys(obj) {
    var keys = [];
    for (var key in obj) {
        keys.push(key);
        if (typeof obj[key] === "object") {
            var subkeys = getDeepKeys(obj[key]);
            keys = keys.concat(subkeys.map(function (subkey) {
                return key + "." + subkey;
            }));
        }
    }
    return keys;
} 
var data = [{ "branch_id": 992, "sale_id": 24422, "identifier": "", "emitter": { "id": 68, "tax_id": "", "address": { "street": "Carretera a buenavista km 21", "country_code": "MEX", } } }];

console.log(getDeepKeys(data));
N. Tobías
  • 55
  • 1
  • 12