Anirudh Anirudh - 3 years ago 88
Javascript Question

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?

Programming Language used: 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" }
]

Answer Source

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.

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. So addType("diesel") is a function which adds type: "diesel" to its argument.

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}))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download