[英]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.到目前为止,这是我尝试过的方法,但我只得到 1 个值作为回报。
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.
Map function是可以对数组执行的,所以我们首先要把object转成数组,然后再对它执行操作。
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. function
Object.keys
单独完成了这个技巧,它返回一个数组,其中包含 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.首先制作您的 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.然后循环遍历第一步创建的object。
//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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.