我想使用条件返回对象内元素之一的键值:
const raw = {
item1: { name: 'sdfd1', otherStuff: { book:'sdfd11' } },
item2: { name: 'sdfd2', otherStuff: { book:'sdfd22' } },
item3: { name: 'sdfd3', otherStuff: { book:'sdfd33' } }
};
var anotherOne = {
country1 : { city: 'one', item: 'item3'},
country2 : { city: 'two', item: 'item4'}
}
var searchTerm = anotherOne.country1.item; // item3
var secondTerm = someUser.otherInfo // 'otherStuff'
var result = Object.keys(raw)
.filter(key => {
if (key === searchTerm){
return raw[searchTerm][secondTerm].book
}})
console.log('result:' result); // sdfd33
基本上,我想在对象 raw
的键中查找 searchTerm
,并返回 book
键的值。在此示例中,它应返回 sdfd33
。
我的尝试没有返回任何内容。
更新:
更新了问题。
最佳答案
在通过变量访问对象键时使用方括号[]
。
希望在这种情况下不需要 filter
和 Object.keys
const raw = {
item1: {
name: 'sdfd1',
book: 'sdfd11'
},
item2: {
name: 'sdfd2',
book: 'sdfd22'
},
item3: {
name: 'sdfd3',
book: 'sdfd33'
}
};
var searchTerm = 'item3';
//using square bracket when acceing key using variable
var result = raw[searchTerm].book
console.log(result);
关于javascript按对象键过滤并返回嵌套对象键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48980942/