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));
8
  • you can loop over a object properties without the use of keys Commented Jun 5, 2018 at 12:51
  • I have seen this answered on this site multiple times. Go look Commented Jun 5, 2018 at 12:51
  • 1
    Make use of Object.keys() Commented Jun 5, 2018 at 12:51
  • 1
    build a recursive function that analyzes the whole array. Commented Jun 5, 2018 at 12:58
  • 2
    Possible duplicate of Access / process (nested) objects, arrays or JSON Commented Jun 5, 2018 at 13:02

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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" } ] } ] } }
be careful with (typeof obj[property] == "object") because: typeof [] === 'object' // true typeof null === 'object' // true typeof new Date() === 'object' // true See: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… In any case, I just gave you a snippet of what you could do, you can adapt it to your own needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.