qts qts - 12 days ago 5x
Javascript Question

Javascript: Adding a property to an array of objects

I have an array of objects as follows:

var myarray=[{"name":"John","address":"home"},{"name":"Peter","address":"home"}]

and I would like to run a function to add a property to the array as follows:


I have tried doing this:

myarray=myarray.map(function (err, myarray){
return myarray;

But the console continues to return this:


Can anyone help me? Thank you


Your code is not adding the property to the contents of the array. The values of the array are given as the first parameter to the callback function (the second parameter is an index, and not the array itself—that's the third parameter). Simply assign the new property to the first parameter of the callback function, rather than the second one.

Edit - As @zerkms points out, however, if you're looking to update the current array rather than generate a new array, map is probably not best solution here. forEach provides a method for iterating over the current array, and modifying each of its values (which is what you're doing). This would looks omething like this:

myarray.forEach(function(value) {
    value.collection = "friend";

As you'll notice in the documentation for .map, the callback function returns the new value that will appear in the new array that is generated by map; if you're changing the current array in place (i.e. by modifying the properties of its contents), there's no need to return anything.

myarray.map(function(value) {
    value.collection = "friend";

Also note that both map and forEach are methods, so you need to close the method invocation with ).