[英]javascript filter by object key and return value of nested object key
我想使用条件返回对象内部元素之一的键值:
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);
您可以简单地返回如下值:
var result = raw.item3.book;
console.log(result);
结果应该是sdfd33
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.