我有这样的(...)
,
json
[
[{id:0, name:test, data:{},other:'...'}],
[{id:1, name:test, data:{},other:'...'}],
[{id:2, name:test, data:{},other:'...'}],
[{id:3, name:test, data:{},other:'...'}],
[{id:4, name:test, data:{},other:'...'}]
]
我想用id=2
获得元素的索引。例如,我已经尝试了多种方法(使用find
,findIndex
),但是它没有用。可能是因为我的搜索功能不正确,所以我来寻求这段代码中的帮助
答案 0 :(得分:1)
var input = [
[{id:0, name:'test', data:{},other:'...'}],
[{id:1, name:'test', data:{},other:'...'}],
[{id:2, name:'test', data:{},other:'...'}],
[{id:3, name:'test', data:{},other:'...'}],
[{id:4, name:'test', data:{},other:'...'}]
]
console.log(input.findIndex(items => items.some(item => item.id === 2)));
答案 1 :(得分:-1)
var test = "test";
var myArray = [
[{id:0, name:test, data:{},other:'...'}],
[{id:1, name:test, data:{},other:'...'}],
[{id:2, name:test, data:{},other:'...'}],
[{id:3, name:test, data:{},other:'...'}],
[{id:4, name:test, data:{},other:'...'}]
];
myIndex = myArray.indexOf(myArray.filter(items => items.some(item => item.id === 2))[0]);
console.log('myIndex: '+ myIndex);