我在更新找到的对象时遇到问题。 我也试过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>
最佳答案
使用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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
关于javascript - 通过属性和值获取数组对象项的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41764706/