How to get the value of an object from a list of keys

I have an object that you see below:

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

and I want to get the value as below:

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

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

I want to encapsulate a requirement in a function:

function get_value(obj, key_list) {

}

because it is key_listnot defined, so how to implement the function?

+4
source share
2 answers

Just use a loop whileand key iterations

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));
Run codeHide result

It would 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));
Run codeHide result
+3
source

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]]
}
+1
source

Source: https://habr.com/ru/post/1695951/


All Articles