1

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>

2
  • foundObj will be array and not the index what do you want ? Commented Jan 20, 2017 at 13:22
  • My question was hidden inside the code snippet. =) Commented Jan 20, 2017 at 13:23

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

2 Comments

You already filtered the element, so you can update it directly instead of re-searching for its index
Yup, that's right - But at least you're demonstrating 2 possible solutions
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.