简体   繁体   English

如何循环遍历 object 并获取每个元素的索引并将其存储在数组中?

[英]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.

相关问题 如何遍历数组对象并检查每个元素以查看是否已定义? - How can I loop through an array object and check each element to see if one is defined? 如何在每个循环中获取 Meteor 模板中数组的索引? - How can I get the index of an array in a Meteor template each loop? 如何获取 object 中数组元素的索引? - How can I get the index of array element inside object? 如何循环遍历 object 数组并从数组中列出的两个对象中获取一个属性元素? - How can I loop through an array of object and get one property element out of the two objects listed inside the array? 如何遍历一个jQuery数组,然后一次输出一项(从索引0开始)? - How can I loop through a jquery array and then output each item (starting at index 0) one at a time? 在将对象数组转换为 xml 时,如何分别摆脱由数组键包裹的每个元素? - How can I get rid of each element wrapped by the array key separately while converting array of object to xml? 我如何循环遍历数组中每个 object 的属性,每个 object 的属性都不同。 这是 Javascript - How do i loop through the properties of each object in the array, the properties are different in each object. This is Javascript 遍历对象数组并将每个元素插入html - Loop through object array and insert each element into html 如何从网页获取JSON对象数组并将每个元素添加到HTML中的行? - How can i get an array of JSON object from a webpage and add each element to the row in HTML? 如何遍历每个元素上调用 jquery.each 的数组? - How to loop through an array calling jquery.each on each element?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM