简体   繁体   English

如何使用字符串/键数组访问 object 属性?

[英]How can I access object properties using an array of strings / keys?

Let us consider the following array and object:让我们考虑以下数组和 object:

const keys = ['a', 'b', 'c'];

const object = {
  a: {
    b: {
      c: {
        data: 1
      }
    }
  }
}

Naturally, I would access the data like so:自然,我会像这样访问数据:

object['a']['b']['c']

The question is, how can I access the data using the array as input?问题是,如何使用数组作为输入来访问数据? Something like:就像是:

object[...keys]

Probably no other way to do this可能没有其他方法可以做到这一点

 const keys = ['a', 'b', 'c']; const object = { a: { b: { c: { data: 1 } } } } console.log(getValue(object, ...keys)) function getValue(obj, ...keys) { let current = obj for (const key of keys) { current = current[key] } return current }

You can loop through the keys:您可以遍历键:

 function getValueAtObjectPath(obj, path) { let val = obj; let key = path.shift(); while(key && val) { val = val[key]; key = path.shift(); }; return val; } const keys = ['a', 'b', 'c']; const object = { a: { b: { c: { data: 1 } } } } let val = getValueAtObjectPath(object, keys); console.log('value at object path: ' + JSON.stringify(val));

Return:返回:

value at object path: {"data":1}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Lodash,如何检查对象的键是否与字符串数组匹配 - Using Lodash, how can I check to see if an object's keys match an array of strings 如何使用键数组访问和更改对象中的值 - How can i access and change a value in an object with an array of keys 如何从数组中的对象访问属性? - How can I access properties from an object within an array? 如何访问对象的属性 - how can i access properties of an object 从对象数组的元素中,如何访问对象的属性/方法。 JS - From an Object's Array's Element, how can I access the Object's properties/methods. Js 如何访问嵌套数组内的对象的属性? - What can I do to access to the properties of an object inside a nested array? 如何使用javascript访问位于对象数组中的对象的属性? - How to access properties of an object that is in an array of object using javascript? 如何让我的默认属性数组访问插件中传递的jQuery对象? - How can I give my default array of properties access to the passed jQuery object in my plugin? 如何使用 JavaScript 访问数组中的特定对象? - How can I access a specific object in my array using JavaScript? 如何从一个对象创建一个字符串数组,其中各个键的值是单独的字符串数组? - How do I create an array of strings from an object where the values of individual keys are separate arrays of strings?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM