0

I'm trying to use an array of strings to access a value nested within an object.

Is there a utility for this already?

let obj= {
  one: {
    two: {
      thee: "test"
    }
  }
}

let values= ["one", "two", "three"]

function accessObjectWithArray(obj, arr) {
    // returns "test"
}
1
  • lodash's _.get(obj, arr) Commented Jun 5, 2018 at 1:44

3 Answers 3

3

Use reduce to iterate through the array of properties:

const obj={one:{two:{three:"test"}}};
const values= ["one", "two", "three"];

const accessObjectWithArray = (obj, arr) => arr.reduce((a, prop) => a[prop], obj);
console.log(accessObjectWithArray(obj, values));

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

Comments

0

There's nothing built into js to do this, but you can make a nice recursive function to do it:

let obj= {
  one: {
    two: {
      three: "test"
    }
  }
}

let values= ["one", "two", "three"]

function accessObjectWithArray(obj, arr) {
    if (!arr.length) return obj;
    return accessObjectWithArray(obj[arr[0]], arr.slice(1));
}

console.log(accessObjectWithArray(obj, values));

Note: You had a typo in the three property which I have fixed

Comments

0

lodash has a nice get function for this:

let obj= {
  one: {
    two: {
      three: "test"
    }
  }
}

console.log(_.get(obj, ['one', 'two', 'three']))

console.log(_.get(obj, 'one.two.three'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

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.