[英]How to insert a fixed property value into every object inside an array without looping?
Is there any way I can insert a fixed value into every object inside an array? 有什么办法可以将固定值插入数组中的每个对象? I'm able to achieve the final output by looping.
我可以通过循环实现最终输出。 Is there any way I can achieve the final output without using a for/while loop?
有没有不用for / while循环就可以达到最终输出的方法?
Programming Language used: JavaScript 使用的编程语言: JavaScript
Example Array: 示例数组:
"cars": [
{ "name":"Ford", "models":"Fiesta" },
{ "name":"BMW", "models":"X1" },
{ "name":"Fiat", "models":"Punto" }
]
Required Array : Need to add type:"diesel" to each object in the array 必需的数组:需要向数组中的每个对象添加类型:“柴油”
"cars": [
{ type:"diesel", "name":"Ford", "models":"Fiesta" },
{ type:"diesel", "name":"BMW", "models":"X1" },
{ type:"diesel", "name":"Fiat", "models":"Punto" }
]
By definition you will have to loop. 根据定义,您将不得不循环。 The only question is whether you write the loop yourself with
for
, or use something like forEach
which loops for you. 唯一的问题是您是使用
for
自己编写循环,还是使用forEach
为您循环的东西。
cars.forEach(car => car.type = "diesel")
Here is a slightly more functional approach: 这是一种稍微实用的方法:
const addType = type => car => car.type = type;
cars.forEach(addType("diesel"))
Yes, this is a bit complicated. 是的,这有点复杂。
addType
creates a function which sets the type
property of whatever is passed to it to some value. addType
创建一个函数,该函数将传递给它的任何内容的type
属性设置为某个值。 So addType("diesel")
is a function which adds type: "diesel"
to its argument. 因此
addType("diesel")
是一个在其参数中添加type: "diesel"
的函数。
Or you could just loop: 或者你可以循环:
for (car of cars) car.type == "diesel";
The above will mutate the original objects. 上面将变异原始对象。 To create an array of new objects with the added property:
要创建一个具有添加属性的新对象数组:
cars.map(car => ({...car, type: diesel}))
You can also use map
to solve your purpose. 您也可以使用
map
解决您的目的。
cars.map((obj) => {
obj.Active = 'false';
return obj;
}
You can use Array#map
. 您可以使用
Array#map
。
var automobile = { "cars": [ { "name":"Ford", "models":"Fiesta" }, { "name":"BMW", "models":"X1" }, { "name":"Fiat", "models":"Punto" } ] } var newArr = automobile["cars"].map((car) =>{ car['type'] = "diesel"; return car; }); console.log(newArr);
Using forEach 使用forEach
var vehicle = {
"cars": [
{ "name":"Ford", "models":"Fiesta" },
{ "name":"BMW", "models":"X1" },
{ "name":"Fiat", "models":"Punto" }
]
}
vehicle.cars.forEach((car) =>{
car.type = "diesel";
return car;
});
console.log(vehicle.cars);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.