如何获取数组的所有索引,
[
{
"name":"aloha",
"age":"18"
},
{
"name":"hello word"
},
{
"name":"John Doe",
"age":"28"
}
]
输出应类似于[0,1,2]
答案 0 :(得分:1)
最简单的方法是(请参见this post):
let a = [{1: 'x'}, {1: 'y'}, {1: 'z'}]
let b = Array.from(a.keys())
console.log(b)
而朴素的解决方案是在数组上调用map((_, i) => i))
:
let a = [{1: 'x'}, {1: 'y'}, {1: 'z'}]
let b = a.map((_, i) => i)
console.log(b)
答案 1 :(得分:0)
您还可以使用Object.keys来检查任何对象的键索引。
let a = [
{
'name' : "aloha",
"age": "18"
},
{
"name": "hello word"
},
{
"name": "John Doe",
"age" : "28"
}]
console.log(Object.keys(a));
答案 2 :(得分:0)
您可以使用forEach循环,例如以下示例:
//The array you want to get all the indexes from
const array = [{'a':1}, {'b':2}, {'c':3}];
//All indexes array
const indexArray = [];
array.forEach((el, i) => {
indexArray.push(i);
});
答案 3 :(得分:-1)
let ary = [
{
'name' : "aloha",
"age": "18"
},
{
"name": "hello word"
},
{
"name": "John Doe",
"age" : "28"
}
]
let outputAry = Array.from(Array(ary.length),(x,index)=>index);
console.log(outputAry);