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
Forsaiken
  • 324
  • 3
  • 12

1 Answers1

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'));
Karan
  • 12,059
  • 3
  • 24
  • 40