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