In your case, your iterating through an array of objects, so the value will be the object at each index, and the key will be the index value (i.e. 0, 1, ...). You want to pass in data
for the object
you refer to.
var data = [{name: "Kevin", country: "Canada"}, {name:"Bob", country: "Spain"}];
angular.forEach(data, function (value, key) {
// Key will be 0 or 1
if (value.country === 'Canada') {
value.country = 'China';
}
});
Because objects are passed by reference in JavaScript, you can edit properties on each object directly, i.e. value.country === 'China'
will change the object inside the actual array.
However, you can only change properties on the object, and if you tried to overwrite the entire object, it wouldn't work.
var data = [{name: "Kevin", country: "Canada"}, {name:"Bob", country: "Spain"}];
angular.forEach(data, function (value, key) {
if (value.country === 'Canada') {
// This won't update the object in data.
value = {
name: value.name,
country: 'China'
};
}
});
If you were iterating through an object with non-object types, you'd have to use the key and edit the object directly, and in the case of passing it an object, the key will be the actual key in the object.
var nyc = { name: 'New York City', state: 'NY' };
angular.forEach(nyc, function (value, key) {
if (key === 'state') {
nyc[key] = 'New York'; // Or, nyc.state since we know what it is
}
});