【问题标题】:javascript filter by object key and return value of nested object keyjavascript按对象键过滤并返回嵌套对象键的值
【发布时间】:2018-02-26 03:16:25
【问题描述】:

我想使用条件返回对象内部元素之一的键值:

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。 我的尝试没有返回任何内容。

更新:

更新了问题。

【问题讨论】:

  • key 只是一个字符串,返回raw[key].book
  • raw[searchTerm].book 是您所需要的。

标签: javascript arrays ecmascript-6 javascript-objects


【解决方案1】:

通过变量访问对象键时使用方括号[]。 希望在这种情况下不需要filterObject.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);

【讨论】:

    【解决方案2】:

    您可以简单地返回如下值:

    var result = raw.item3.book;
    
    console.log(result);
    

    结果应该是 sdfd33

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 2022-01-12
      • 2022-10-14
      • 2019-03-02
      • 1970-01-01
      • 2019-02-22
      • 1970-01-01
      • 2021-09-27
      相关资源
      最近更新 更多