I\'ve got an array of objects and I need a function that finds object an array by the objects property (id
in example) and changes its other property (name
Use this instead of filter. Filter produce new array.
arrayOfObjects.forEach(function(v){
if (v.id == id) {v.name = newName}
});
Use Array#forEach
over Array#filter
Note that ==
or ===
should be used to compare, =
will assign the value!
Array#forEach
with condition should be enough just to update existing array of object.
var arrayOfObjects = [{
id: 1,
name: 'Alpha'
}, {
id: 2,
name: 'Bravo'
}];
var setNameById = function(id, newName) {
var filtered = arrayOfObjects.filter(function(obj) {
return obj.id == id;
});
filtered.forEach(function(el) {
el.name = newName;
});
return filtered;
};
console.log(JSON.stringify(arrayOfObjects));
var filtered = setNameById(2, 'Charlie');
console.log(JSON.stringify(filtered));
Or use Array#map
var arrayOfObjects = [{
id: 1,
name: 'Alpha'
}, {
id: 2,
name: 'Bravo'
}];
var setNameById = function(id, newName) {
return arrayOfObjects.filter(function(obj) {
return obj.id == id;
}).map(function(el) {
el.name = newName;
return el;
});
};
console.log(JSON.stringify(arrayOfObjects));
var filtered = setNameById(2, 'Charlie');
console.log(JSON.stringify(filtered));
Filter returns an array. So will have to use index
in your approach.
var arrayOfObjects = [{
id: 1,
name: 'Alpha'
}, {
id: 2,
name: 'Bravo'
}];
var setNameById = function(id, newName) {
arrayOfObjects.filter(function(obj) {
return obj.id = id;
})[0].name = newName;
};
console.log(JSON.stringify(arrayOfObjects)); // initial array logged
setNameById(2, 'Charlie');
console.log(JSON.stringify(arrayOfObjects));
If you are sure it will return only one value, use array.find
var arrayOfObjects = [{
id: 1,
name: 'Alpha'
}, {
id: 2,
name: 'Bravo'
}];
var setNameById = function(id, newName) {
arrayOfObjects.find(function(obj) {
return obj.id = id;
}).name = newName;
};
console.log(JSON.stringify(arrayOfObjects)); // initial array logged
setNameById(2, 'Charlie');
console.log(JSON.stringify(arrayOfObjects));
If there can be more than 1 object with same search key (id in this case), use array.forEach
instead of array.filter
and then loop over filtered array
var arrayOfObjects = [{
id: 1,
name: 'Alpha'
}, {
id: 2,
name: 'Bravo'
}];
var setNameById = function(id, newName) {
arrayOfObjects.forEach(function(obj) {
if(obj.id = id) obj.name = newName;
});
};
console.log(JSON.stringify(arrayOfObjects)); // initial array logged
setNameById(2, 'Charlie');
console.log(JSON.stringify(arrayOfObjects));