0

Is there an equivalent in Javascript for this following functionality achieved through Java?

To be able to iterate through an simple to complex/ nested JSON structure without knowing the JSON format.

I am in need of this functionality to get hold of all the innermost keys and that hold a direct value and not object/array as its value.

In this fiddle, Object.keys() only gives the outermost keys. I want to be able to get (id, type)

console.log(Object.keys(x));
we bendthetrend
  • 49
  • 1
  • 10

1 Answers1

1

You can build it yourself, just iterate the keys of the object recursively if it is an object, see this small example:

    const getAllPropertiesRecursively = (obj) => {
    const propertyKeys = [];
    Object.keys(obj).forEach(key => {
        const value = obj[key];
        if (value && !Array.isArray(value)) {
            if (value.toString() === '[object Object]') {
                propertyKeys.push(...getAllPropertiesRecursively(value));
            } else {
                propertyKeys.push({[key]: value}); // here you store the keys and values that are not array nor object
            }
        }
    });
    return propertyKeys;
}

So when you call this method like this:

getAllPropertiesRecursively({a:1, b:2, c: { d: 1}, e: [1,2,3,4], f: {g:2}});

You get an array like:

[{a: 1}, {b: 2}, {d: 1}, {g: 2}]

You can edit the line with the comment to store the data in the way you want

A. Llorente
  • 1,142
  • 6
  • 16
  • Consider this data : key array is empty : { "i": { "i1": [{ "id": "0001", "b": { "b1": [{ "d1": "t1", "coordinates": [19.291422,73.53197 ] }, { "d3": "t3", "d4": "t4" } ] }, "c": [{ "d5": "t5", "r1": ["1", "2", "3"] }, { "d6": "t6" } ] }, { "id": "0002", "b": { "b1": [{ "d1": "t1", "d2": "t2" }, { "d3": "t3", "d4": "t4" } ] }, "c": [{ "d5": "t5" }, { "d6": "t6" } ] } ] } } – we bendthetrend Jun 06 '18 at 05:17
  • be careful with (typeof obj[property] == "object") because: typeof [] === 'object' // true typeof null === 'object' // true typeof new Date() === 'object' // true See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof In any case, I just gave you a snippet of what you could do, you can adapt it to your own needs. – A. Llorente Jun 06 '18 at 06:33