通过使用字符串数组作为路径动态访问嵌套对象

通过使用字符串数组作为路径动态访问嵌套对象

问题描述:

我正在尝试实现一种通用方法来动态访问嵌套对象属性.

I'm trying to implement a generic method to access a nested object property dynamically.

该属性的路径必须位于字符串数组中.

The path to the property have to be in an array of string.

因此要获取标签,字符串数组应为['type', 'label']

So to get the label the array of string would be ['type', 'label']

我有点困扰这个问题,有什么帮助吗?

I'm kinda stuck on this problem, any help ?

**编辑片段:**

**Edit snipet : **

演示

var parent = {
  type: {
    id: "2",
    label: "3",
  }
};

function getNestedLabel(ids){
if (ids.length === 1) {
  return parent[ids[0]];
}
var result = parent;
for (let i = 0; i < ids.length; i++) {
  result = result[ids[i]];
}
return result;
  }

console.log(getNestedLabel(["type", "label"]));

一种简单的方法是迭代keyArray并同时使用 keys 遍历 object 来自keyArray

A simple approach would be to iterate the keyArray and also keep traversing the object with keys from keyArray

function getNestedObject( keyArr ){
    var tmp = parent; //assuming function has access to parent object here
    keyArr.forEach( function(key){
       tmp = tmp[key];
    });
    return tmp;
}

演示

var parent = {
  type: {
    id: "2",
    label: "3",
  }
};

function getNestedObject(keyArr) {
  var tmp = parent; //assuming function has access to parent object here
  keyArr.forEach(function(key) {
    tmp = tmp[key];
  });
  return tmp;
}

console.log( getNestedObject( [ "type", "label" ] ) );