问题描述
我正在尝试访问对象的键。 但这不起作用。有人可以帮我吗?
所以我有一个对象和一个指向我必须在对象内部访问的值的字符串。而且该值下降了两个级别。
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.
解决方法
您的问题的粗略解决方案:
config.api_only = true
这是一个更好的不使用 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
如果key ref(上面提到的item)的格式是固定的并且用'.'分隔,我们可以拆分key然后使用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);