如何通过键列表获取对象的值

时间:2022-12-22 23:50:14

I have a obj you see bellow:

我有一个obj你看到吼叫:

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?

因为key_list不确定,所以如何实现这个功能呢?

2 个解决方案

#1


3  

Just use a while loop and iterate over the keys

只需使用while循环并迭代键

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));

#2


1  

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


3  

Just use a while loop and iterate over the keys

只需使用while循环并迭代键

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));

#2


1  

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]]
}