通过使用字符串数组作为路径动态访问嵌套对象 [英] Access nested object dynamically by using array of string as a path

查看:96
本文介绍了通过使用字符串数组作为路径动态访问嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于通过使用字符串数组作为路径动态访问嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆