【问题标题】:How do I access the filelds of an object, with an string that is pointing to direction of value in object如何使用指向对象中值方向的字符串访问对象的字段
【发布时间】:2021-03-24 15:17:44
【问题描述】:

我正在尝试访问对象的键。 但这行不通。有谁能帮帮我吗?

所以我有一个对象和一个指向我必须在对象内部访问的值的字符串。而且这个值下降了两个级别。

const obj = { name: 'yash', { hobbies: { sports: ['football', 'tennis']} } };
// this is an example object, I have a string
const item = 'hobbies.sports';
// now I want to access the object with this item
obj[item] // but this isn't working.

【问题讨论】:

标签: javascript object data-structures javascript-objects


【解决方案1】:

如果key ref(item)的格式是固定的,并用'.'分隔,我们可以拆分keys,然后使用reduce得到如下结果-

const obj = { name: 'yash', hobbies: { sports: ['football', 'tennis']} };
const ref = 'hobbies.sports';

const keys = ref.split('.');
const result = keys.reduce((accumulator, x) => accumulator[x], obj);

console.log(result);

【讨论】:

    【解决方案2】:

    您的问题的粗略解决方案:

    const obj = {
      name: 'yash',
      hobbies: {
        sports: ['football', 'tennis']
      }
    };
    // this is an example object, I have a string
    const item = 'hobbies.sports';
    // now I want to access the object with this item
    console.log(eval("obj." + item))

    这里有一个更好的不使用eval

    const obj = {
      name: 'yash',
      hobbies: {
        sports: ['football', 'tennis']
      }
    };
    // this is an example object, I have a string
    const item = 'hobbies.sports';
    // now I want to access the object with this item
    output = item.split('.').reduce((acc, el) => acc[el], obj)
    
    console.log(output)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      • 2013-04-16
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      相关资源
      最近更新 更多