How to add attribute or property to an array of objects in JavaScript?
We can add an attribute or property to an array of objects in JavaScript in multiple ways. We can use forEach loop and then add the attribute. We can use the array map method to loop over and add the attribute.
Following are the examples:
By using map
const userList = [ {name: 'Joe Smith', age: 25}, {name: 'Jennifer Smith', age: 20} ]; const modifiedUserList = userList.map(userObj => ({ ...userObj, status: 'active' })); console.log(userList); console.log(modifiedUserList);
By using forEach
const userList = [ {name: 'Joe Smith', age: 25}, {name: 'Jennifer Smith', age: 20} ]; userList.forEach(userObj => { userObj.status = 'active'; }); console.log(userList);
Reference: