Javascript对象数组:返回值的最佳方法?

时间:2018-07-09 12:07:27

标签: javascript

我有一个Javascript对象数组,带有两个具有这种结构的键:

<SectionList 
      sections={this.state.data.filter(sectionData => {
        sectionData = sectionData.data;
        return sectionData.filter(data => {
          return data.includes(this.state.searchTerm);
        })
      })}
      renderSectionHeader={({ section: { title } }) => ( <Text style={{ fontWeight: "bold" }}>{title}</Text> )}
      renderItem={({ item }) => ( <Text style={styles.listItem}>{item}</Text>)}
      keyExtractor={item => item}
    />

我想给它传递一个'type'数值,如果它在数组中找到它,就给我返回描述值。例如,如果我传递“ 0”,我希望它返回“未知”。

这可以轻松地通过for或forEach循环来完成,但是JS中有一个内置函数可以让我在一行中完成它?

3 个答案:

答案 0 :(得分:6)

您可以使用find

var data = [{ description: "Unknown", type: 0 }, { description: "On", type: 1 }, { description: "Off", type: 2 }];
  
console.log(data.find(({ type }) => type === 1).description);

或者为了更快地访问,请为类型使用哈希表

var data = [{ description: "Unknown", type: 0 }, { description: "On", type: 1 }, { description: "Off", type: 2 }], 
    types = Object.assign(...data.map(({ type, description }) => ({ [type]: description })));
  
console.log(types[1]);

Map

var data = [{ description: "Unknown", type: 0 }, { description: "On", type: 1 }, { description: "Off", type: 2 }], 
    types = data.reduce((m, { type, description }) => m.set(type, description), new Map);
  
console.log(types.get(1));

答案 1 :(得分:0)

您可以Filter列表中的一个。

var obj=[{
  "description": "Unknown",
  "type": 0
  },
  {
  "description": "On",
  "type": 1
  },
  {
  "description": "Off",
  "type": 2
  }];
  var filterType=1;
  console.log(obj.filter(e=>e.type == filterType)[0]['description'])

答案 2 :(得分:0)

看看附带的代码段,它给出了所需的输出。

  • 查找函数遍历整个数组以匹配条件,即在这种情况下,passedIndex将检查其是否存在于列表中

  • 如果有的话,退还物品

var list = [{
    "description": "Unknown",
    "type": 0
  },
  {
    "description": "On",
    "type": 1
  },
  {
    "description": "Off",
    "type": 2
  }
];

function findItem(index) {
  var result = list.find(function(item) {
    if (item.type == index) {
      return item;
    }
  });
  return result.description;
}
var description = findItem(2);
console.log('The Description is "' + description + '"')