sof-03
sof-03

Reputation: 2505

How to get a object's value by a key list

I have a obj you see bellow:

var obj = {
  a: {
    b:{
      c:"c"
    }
  }
}

and I want to get value like bellow :

var t = ["a", "b", "c"]  // give a key list

console.log(obj["a"]["b"]["c"])  // and get value like this.

in depth, I want to encapsulate the requirement in a function:

function get_value(obj, key_list) {

}

because the key_list is not certain, so how to realize the function?

Upvotes: 4

Views: 119

Answers (2)

Isaac
Isaac

Reputation: 11805

Recursive solution:

function get_value(obj, key_list, i) {
  if (i == undefined) {
    i = 0;
  }
  if (i < key_list.length - 1) {
    return get_value(obj[key_list[i]], key_list, i+1)
  }
  return obj[key_list[i]]
}

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 371203

Just use a while loop and iterate over the keys

var obj = {
  a: {
    b:{
      c:"c"
    }
  }
}
var t = ["a", "b", "c"];
function get_value(obj, key_list) {
  let currentReference = obj;
  while (key_list.length !== 0) {
    currentReference = currentReference[key_list[0]];
    key_list = key_list.slice(1);
  }
  return currentReference;
}
console.log(get_value(obj, t));

It'd be more elegant with reduce though:

var obj = {
  a: {
    b:{
      c:"c"
    }
  }
}
var t = ["a", "b", "c"];
function get_value(obj, key_list) {
  return key_list.reduce((currentReference, key) => currentReference[key], obj);
}
console.log(get_value(obj, t));

Upvotes: 3

Related Questions