javascript - 对象数组上的 indexOf 而不是数组

标签 javascript ecmascript-6

<分区>

我知道可以使用 indexOf 来查找数组中存在或不存在的值,但是如何使用对象数组来做到这一点?

const x = [{
  "id": "roadshows",
  "name": "Roadshows"
}, {
  "id": "sporting_events",
  "name": "Sporting Events"
}]

console.log( x.indexOf('roadshows') ) // don't work

最佳答案

因为这被标记为 ,这是一个 ES6 数组方法:Array#findIndex() :

const x = [{
  "id": "roadshows",
  "name": "Roadshows"
}, {
  "id": "sporting_events",
  "name": "Sporting Events"
}]

console.log( x.findIndex( o => o.id === 'roadshows' ) )

如果您想要一种更可重用的方式来执行此操作,请考虑创建一个工厂 isId(id):

function isId(id) {
  return (o) => o.id === id;
}

const x = [{
  "id": "roadshows",
  "name": "Roadshows"
}, {
  "id": "sporting_events",
  "name": "Sporting Events"
}]

console.log( x.findIndex( isId('roadshows') ) )

这被称为“工厂”,因为它是一个函数,它返回一个在其范围内传递参数的函数。

关于javascript - 对象数组上的 indexOf 而不是数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44299912/

相关文章:

javascript - JS等待CSS背景图片加载

javascript - 在尴尬的地方添加到 JS 对象

javascript - 如何在 Angular 组件中手动运行摘要

javascript - 如何向动态嵌套元素添加 onclick 事件?

Javascript ES6 绑定(bind)错误 react

javascript - Vuejs Es6 类 react 性

javascript - 如何使用ReactJS(和react-router)将props传递到react-router中

javascript - React 中 setState 处理程序的问题

javascript - Redux-Saga 以某种方式在不经过 saga 的情况下进行 reducer 更新

node.js - 如何在 Node 中使用 for..of 迭代 map 的键和值?