按属性和值获取数组的对象项的索引

时间:2017-01-20 13:20:34

标签: javascript jquery arrays javascript-objects

我遇到了更新找到的对象的麻烦。 我还尝试了Find object by id in an array of JavaScript objectsGet 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>

2 个答案:

答案 0 :(得分:3)

使用find获取对象,然后使用找到的对象的索引替换元素

&#13;
&#13;
// 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;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用Array#find并检查并更新属性。

&#13;
&#13;
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;
&#13;
&#13;