如何在Javascript中获取数组[Array [{JSON}]]中元素的索引

时间:2019-09-11 16:23:54

标签: javascript arrays

我有这样的(...)

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获得元素的索引。例如,我已经尝试了多种方法(使用findfindIndex),但是它没有用。可能是因为我的搜索功能不正确,所以我来寻求这段代码中的帮助

2 个答案:

答案 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);