简体   繁体   中英

How can I loop through an object and get the index of each element and store it in an array?

Here is what I have tried so far but I am only getting 1 value in return.

Object.keys(yelpResults).map((key) => {
  return setRestaurantIndexes(restaurantIndexes.concat(key));
});

you can refer this example if it helps. Map function can be executed on array, so first we need to convert object into array and then execute operation on it.

const details={
  name:'John',
  lName:'lee',
  country:'US'
}

const getIndex = Object.keys(details).map((item , i)=>{
  return i;  
});

console.log(getIndex);

The function Object.keys alone do the trick, it returns an array with the names of the properties and methods of an object.

const data = {
  name: 'John Doe',
  age: 50,
  country: 'NZ'
}

const propertyNames = Object.keys(data)

console.log(propertyNames);
// prints: ['name', 'age', 'country']
  • First make your object.

     const result = ["Apple", "Orange", "Plum"];
  • Then declare an array where you will save your index values

    let newArray = []
  • Then loop through the object created at step 1.

     //loop the results for(var i=0, l=result.length; i < l; i++){ //push the object's index to the array newArray.push(i); }
  • Console Log your new array with index values saved in it.

     console.log(newArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM