1

Let's use this object as example:

var obj = {a: {b: {c: 'result'}}}

I know that I can get the value of c, doing this:

console.log(obj.a.b.c) // 'result'

or this:

console.log(obj['a']['b']['c'])

but how I can get the value of c passing obj and columns as arguments in a function?

function func(obj, attributes) {
   return obj[attributes]
}

console.log(func(obj, a.b.c)) // how to make this work
console.log(func(obj, ['a']['b']['c'])) // or this
2

1 Answer 1

2

You can pass attributes as string like 'a.b.c'. Then split it and use reduce to get desired value.

Test it below.

var obj = {a: {b: {c: 'result'}}}
function func(obj, attributes) {
  return attributes.split('.').reduce((x, a) => x[a], obj);
}

console.log(func(obj, 'a.b.c'));
console.log(func(obj, 'a.b'));

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.