4

I have a nested object of which I do not know the structure of. For example:

const nestedObject = {
  "one": {
    "two": {
       "three": 3
     }
  }
}

I wanted to display value of three.

I have an array like this so that I know how to navigate the object in order to get to three:

const keys = ["one", "two", "three"]

This doesn't have to be structured this way.

So how do I access one.two.three given the keys array above? Or some other data structure. I was thinking of doing a recursion, but it seems too complex and I feel like there is a simple solution out there.

2

2 Answers 2

11

You can do it with a simple Array.prototype.reduce() function:

const data = {
  "one": {
    "two": {
       "three": 3
     }
  }
};

const keys = ["one", "two", "three"];

const value = keys.reduce((a, v) => a[v], data);

console.log(value);

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

Comments

0

You can use MyObject["fieldName"] to access the sub object. And then, you can use a recursive function that will use the array containing the indexes to roam through the object

let MyObj = {
  "one": {
    "two": {
       "three": 3
     }
  }
};

let Keys = ["one", "two", "three"];

function getValue(obj, arrIndexes, index = 0)
{
  let currentIndex = arrIndexes[index];
  let currentObject = obj[currentIndex];
  
  if (index < arrIndexes.length - 1)
  {
    return getValue(currentObject, arrIndexes, index + 1)
  }
  else
  {
    return currentObject;
  }
}

console.log(getValue(MyObj, Keys));

Comments

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.