简体   繁体   English

如何在对象数组中设置每个对象的属性?

[英]How to set a property of each object inside an array of objects?

I have this array as example: 我以这个数组为例:

array = [{id:3},{id:2},{id:4}]

I want to loop through this array of objects, and make each "id" from each object equal to its index position inside of the array, to make something like this: 我想遍历此对象数组,并使每个对象中的每个“ id”等于其在数组内部的索引位置,以进行如下操作:

array =[{id:0},{id:1},{id:2}]

Any idea of how can I do this? 关于如何执行此操作的任何想法?

Thank you all for the attention! 谢谢大家的关注!

Simple map would work: 简单的map可以工作:

 const array = [{id:3},{id:2},{id:4}]; const newArray = array.map((e, i) => ({ id: i })); console.log(newArray); 
 .as-console-wrapper { max-height: 100% !important; top: auto; } 

If you want to keep all other properties the same (if you have multiple properties): 如果要保持所有其他属性相同(如果有多个属性):

 const array = [{id:3, name: "A"},{id:2, name: "B"},{id:4, name: "C"}]; const newArray = array.map((e, i) => ({ ...e, id: i })); console.log(newArray); 
 .as-console-wrapper { max-height: 100% !important; top: auto; } 

Using forEach metohd will loop to every object in the array then to change a property value of an object to the index of the element you must pass the object and its index as the second args then equate it to the object property. 使用forEach metohd将循环到数组中的每个对象,然后将对象的属性值更改为元素的索引,您必须将该对象及其索引作为第二个args传递,然后将其等同于object属性。

let array = [{id:3},{id:2},{id:4}] 
 array.forEach((item, index) => { 
 item.id = index 
})

For completeness, you can loop over an array with a simple for loop: 为了完整起见,您可以使用简单的for循环遍历数组:

for (var i = 0; i < array.length; i++) {
  array[i].id = i;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript:如何为对象数组中的 object 属性设置值? - Javascript: How to set value to an object property inside an array of objects? 如何在对象数组中为每个 object 添加带有值的键? - How to add the key with value for each object inside an array of objects? 如何在对象数组中分离每个对象的键和值-Javascript - How to separate key and value of each object inside array of objects - Javascript 将属性附加到对象数组中的每个 object - Appending a property to each object in an array of objects 获取对象数组内对象属性的值 - Get value of object property inside array of objects 对象数组内的特定对象的trim属性 - trim property of specific object inside array of objects 如何将每个 object 具有元素数组的对象列表转换为以子元素作为属性的对象数组 - How to convert a list of objects with each object having an array of elements, to an array of objects with the subelement as a property 如何在VueJS中的promise中设置数组对象属性的值? - How to set value of array object property inside a promise in VueJS? 如何根据每个 object 中的数组从 object 数组中返回某些对象? - How can I return certain objects from object array based on an array inside each object? 如何将对象的属性与对象数组的属性匹配? - How to match a property of an object to a property of an array of objects?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM