Add Property to Every Object in Array - Codewars Javascript
This challenge involves adding a new property to every object within an array. Here's how you can approach it in JavaScript:
Understanding the Problem
The task requires you to take an array of objects, each with its own properties, and add a new property to each object within that array. For example, let's say you have an array of "users" with properties like "name" and "age". You want to add a new property called "isVerified" to each user object.
Solution with forEach
Loop
One common way to achieve this is using the forEach
method. This method iterates through each element in the array and allows you to perform an action on each element.
function addPropertyToEachObject(array, propertyName, value) {
array.forEach(object => {
object[propertyName] = value;
});
return array;
}
let users = [
{ name: "John", age: 30 },
{ name: "Jane", age: 25 },
{ name: "Peter", age: 40 }
];
addPropertyToEachObject(users, "isVerified", true);
console.log(users);
Explanation:
- The
addPropertyToEachObject
function takes an array (array
), a property name (propertyName
), and a value (value
) as arguments. - The
forEach
method iterates through eachobject
in thearray
. - For each object, we use bracket notation (
object[propertyName] = value;
) to add the new property with the specified name and value. - The function returns the modified array.
Solution with map
Method
Another way to achieve this is with the map
method. This method creates a new array by applying a function to each element of the original array.
function addPropertyToEachObject(array, propertyName, value) {
return array.map(object => {
return { ...object, [propertyName]: value };
});
}
let users = [
{ name: "John", age: 30 },
{ name: "Jane", age: 25 },
{ name: "Peter", age: 40 }
];
users = addPropertyToEachObject(users, "isVerified", true);
console.log(users);
Explanation:
- The
addPropertyToEachObject
function takes the same arguments as before. - The
map
method iterates through eachobject
in thearray
. - For each object, we use the spread syntax (
...object
) to create a new object with all the existing properties, and then add the new property with bracket notation ([propertyName]: value
). - The function returns the new array created by the
map
method.
Both methods achieve the same goal, but the forEach
method modifies the original array, while the map
method creates a new array without changing the original one. Choose the method that best suits your needs and coding style.