我遇到了更新找到的对象的麻烦。 我还尝试了Find object by id in an array of JavaScript objects和Get JavaScript object from array of objects by value or property
请帮忙。
// 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>
答案 0 :(得分:3)
使用find获取对象,然后使用找到的对象的索引替换元素
// 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);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:1)
您可以使用Array#find
并检查并更新属性。
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);
&#13;