Javascript 对象数组而不是数组上的indexOf
我知道在数组中查找值是否存在,我可以使用indexOf,但如何使用对象数组Javascript 对象数组而不是数组上的indexOf,javascript,ecmascript-6,Javascript,Ecmascript 6,我知道在数组中查找值是否存在,我可以使用indexOf,但如何使用对象数组 const x = [{ "id": "roadshows", "name": "Roadshows" }, { "id": "sporting_events", "name": "Sporting Events" }] console.log( x.indexOf('roadshows') ) // don't work 由于对象在数组中,所以必须循环 for(var i = 0; i < x
const x = [{
"id": "roadshows",
"name": "Roadshows"
}, {
"id": "sporting_events",
"name": "Sporting Events"
}]
console.log( x.indexOf('roadshows') ) // don't work
由于对象在数组中,所以必须循环
for(var i = 0; i < x.length; i++) {
if (x[i].id== 'roadshows') {
console.log(i);
break;
}
}
我会这样做:
for(let item of x) {
if ( item.hasOwnProperty('id') && item['id'] == 'roadshows' ) {
//do your stuff here
}
}
你有两个选择 首先也是最重要的。您向它传递一个函数,该函数测试一个元素是否是您要查找的元素,它返回使该函数返回
true
的第一个元素的索引
x.findIndex((o) => o.id === 'roadshows');
const x=[{
“id”:“路演”,
“名称”:“路演”
}, {
“id”:“体育赛事”,
“名称”:“体育赛事”
}];
log(x.findIndex((o)=>o.id==='roadshows')代码>因为这是标记的,所以这里有一个ES6数组方法:
const x=[{
“id”:“路演”,
“名称”:“路演”
}, {
“id”:“体育赛事”,
“名称”:“体育赛事”
}]
console.log(x.findIndex(o=>o.id=='roadshows'))
如果您可以使用es6并希望返回有问题的对象,那么总是会有Array.prototype.find()
OBVOLUY indexOf仅适用于基元类型值。你必须在阵列中循环,没有内置函数可以实现这一点。您可以使用下划线.js或lodash之类的库来实现。否则您必须编写自己的循环。x.map(o=>o.id).indexOf('roadshows')
x.findIndex(o=>o.id=='roadshows')
x.findIndex((o) => o.id === 'roadshows');
x.find( item => { return item.id === "roadshows" } )
// returns {id: "roadshows", name: "Roadshows"}