skip to Main Content

I need to extract a JSON value starting from my variable.
for example i have this json

const myJson = {
  "id": "someID",
  "organizations": [
    "0": {
      "id": "organizationId",
      "name": "organizationName"
    },
    "1": {
      ...
    },
    ...
  ] 
}

and this variable

var pathOfKey = ["organizations","0","id"];

how to get the value of ‘organizationId’ from my variable ‘pathOfKey’?

I don’t know in advance what the path to my key is but I have a variable with this information.
I need to get all the organization IDs of my array.

3

Answers


  1. Basically you need to iterate pathOfKey array and traverse the object with key in the array simultaneously.

    function getValueFromObject(obj, path) {
      let currentNode = obj;
    
      for (key of path) {
        if (!currentNode.hasOwnProperty(key)) {
          return null;
        }
        currentNode = currentNode[key];
      }
      
      return currentNode;
    }
    
    getValueFromObject(myJson, pathOfKey)
    
    Login or Signup to reply.
  2. let obj = {
    "a": {"b": "value"}
    }
    
    let tmpObj = obj;
    let arr = ["a", "b"];
    
    arr.forEach((objKey) => {
      if (tmpObj[objKey] !== undefined) {
        tmpObj = tmpObj[objKey];
      }
    });
    
    console.log(tmpObj);

    Something like this will do the job.
    Also, it can be done with a recursion function

    Login or Signup to reply.
  3. The easiest solution is probably to use reduce().

    const value = pathOfKey.reduce((item, key) => item[key], myJson);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search