最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can i get all index of array - Stack Overflow

programmeradmin1浏览0评论

How can i get all index of array,

[  
   {  
      "name":"aloha",
      "age":"18"
   },
   {  
      "name":"hello word"
   },
   {  
      "name":"John Doe",
      "age":"28"
   }
]

Output should be like [0,1,2]

How can i get all index of array,

[  
   {  
      "name":"aloha",
      "age":"18"
   },
   {  
      "name":"hello word"
   },
   {  
      "name":"John Doe",
      "age":"28"
   }
]

Output should be like [0,1,2]

Share Improve this question edited May 10, 2019 at 12:59 Mandeep Gill 4,9172 gold badges31 silver badges35 bronze badges asked May 10, 2019 at 9:52 AlexCAlexC 952 silver badges7 bronze badges 2
  • 2 Please refer this AlexC stackoverflow./help/how-to-ask. Consider trying something before asking question. – manish kumar Commented May 10, 2019 at 9:54
  • every array index start form zero and end at the number one less than the length of array. what you want to ask, ask properly – Faiz Khan Commented May 10, 2019 at 9:57
Add a ment  | 

3 Answers 3

Reset to default 7

Simplest way would be to (see this post):

let a = [{1: 'x'}, {1: 'y'}, {1: 'z'}]
let b = Array.from(a.keys())
console.log(b)

and the naive solution is by calling map((_, i) => i)) on your array:

let a = [{1: 'x'}, {1: 'y'}, {1: 'z'}]
let b = a.map((_, i) => i)
console.log(b)

You can use Object.keys also to check keys index of any object.

let a = [
        {
        'name' : "aloha",
        "age": "18"
        },
        {
        "name": "hello word"
        },
        {
        "name": "John Doe",
        "age" : "28"
    }]
    
console.log(Object.keys(a));

You can use forEach loop, like this example:

//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);
});
发布评论

评论列表(0)

  1. 暂无评论