[Vuejs]-How to read the dynamic objects data present in JSON?

0πŸ‘

I think that’s not the best api you are using, you should have constant object parameters that you always know how to find things. If you want to find not known parameters you can parse JSON to object and loop throug it.

const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
  console.log(`${property}: ${object[property]}`);
}

0πŸ‘

You can simply achieve that by iterating over Object.keys().

Demo :

const jsonData = {
  "context": [
    {
      "one": "https://example.one.com"
    },
    {
      "two": "https://example.two.com"
    },
    {
      "three": "https://example.three.com"
    }
  ],
  "name": "Batman",
  "age": "30",
  "one:myField": {
    "two:myField2": "Hello"
  },
  "three:myField3": "Hello2"
};

Object.keys(jsonData).forEach(key => {
    if (typeof jsonData[key] === 'object') {
    Object.keys(jsonData[key]).forEach(innerObjKey => {
        console.log(innerObjKey, jsonData[key][innerObjKey])
    })
  } else {
     console.log(key, jsonData[key])
  }
})

0πŸ‘

Combining Object.keys with a recursive function, even if you have multiple nested objects, it will work without having to refactor your code everytime!

const jsonData = {
    context: [
        {
            one: "https://example.one.com",
        },
        {
            two: "https://example.two.com",
        },
        {
            three: "https://example.three.com",
        },
    ],
    name: "Batman",
    age: "30",
    "one:myField": {
        "two:myField2": "Hello",
        "one_nested:myField": {
            another_nested_key: "another_nested_value",
        },
    },
    "three:myField3": "Hello2",
};

recursive(jsonData);

function recursive(nestedKey) {
    if (typeof nestedKey !== "object") return;

    Object.keys(nestedKey).forEach((key) => {
        if (typeof nestedKey[key] === "object") {
            recursive(nestedKey[key]);
        } else {
            console.log(key, nestedKey[key]);

            // add your conditions here

            if (key === "name") {
                // bla bla bla
            }
        }
    });
}

Leave a comment