1
[{id:1,price:10},{id:2,price:20}]

How can I update the price to 200 for array of objects of id 2?

var obj = [{id:1,price:10},{id:2,price:20}];
for(var i=0;i<obj.length;i++){
        if(obj[i].id == 2){
          //what to do here?
        }
      }

I can proceed with push and splice etc but the challenge is to keep the position too.

3 Answers 3

3

You can do:

obj[i].price = 200;
break;

The break will prevent you to continue looping over all the items (since you found the one you were searching for).

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

2 Comments

I don't think a loop would even be needed with an object literal just to access a property...
does this same with return false?
0

Or shorter with Array#forEach():

var obj = [{ id: 1, price: 10 }, { id: 2, price: 20 }];

obj.forEach(function (a) {
    if (a.id === 2) {
        a.price = 200;
    }
});

document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');

2 Comments

this is cleaner, is forEach supported in all browser?
please have a look here: Browser compatibility
0
[{id:1,price:10},{id:2,price:20}].forEach(function(a){ (a.id===2) ? a.price=200 : a});

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.