Reputation: 3098
I'm having troubles with updating found object. I also tried Find object by id in an array of JavaScript objects and Get JavaScript object from array of objects by value or property
Please help.
// Create array
var schedule = [];
schedule.push({ 'action': 'add', 'id': 1 });
schedule.push({ 'action': 'update', 'id': 2 });
// Find array object
var searchId = 2;
var foundObj = schedule.filter(function(obj) { return obj.id == searchId; })
// Update found object
if (typeof foundObj !== 'undefined') {
var newId = 3;
schedule[foundObj] = {'action': 'delete', 'id': newId };
}
console.log(schedule);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Upvotes: 1
Views: 84
Reputation: 386736
You could use Array#find
and check and update the properties.
var schedule = [{ action: 'add', id: 1 }, { action: 'update', id: 2 }],
searchId = 2,
newId = 3,
foundObj = schedule.find(function(obj) { return obj.id == searchId; })
if (foundObj) {
foundObj.action = 'delete';
foundObj.id = newId;
}
console.log(schedule);
Upvotes: 1
Reputation: 4876
Use find to get the object and then use index of found object to replace element
// Create array
var schedule = [];
schedule.push({ 'action': 'add', 'id': 1 });
schedule.push({ 'action': 'update', 'id': 2 });
// Find array object
var searchId = 2;
var foundObj = schedule.find(function(obj) { return obj.id == searchId; })
// Update found object
if (typeof foundObj !== 'undefined') {
var newId = 3;
schedule[schedule.indexOf(foundObj )] = {'action': 'delete', 'id': newId };
}
console.log(schedule);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Upvotes: 3