0

I have one list as follows

var data = [{id:1, name:'user1', img:'img1.jpg' },{id:2, 'user2', img:'img2.jpg' }]

Now I have to replace img property with new value (e.g. 'New_Image_2.jpg') for id=2 using underscore.js or in javascript using less effort. right now I have created one small function as follows.

var imgpath = 'New_Image_2.jpg';
var tmpdata = _.findWhere(data,{id:2});
if (tmpdata) {
    tmpdata.img = imgpath;
}

Now, in above method, my problem is, How to marge new value with original data?

3
  • 3
    Please execute your program and check. Its already working fine. Commented Jun 13, 2014 at 14:07
  • _.findWhere(data,{id:2}); returns the actual object and you are mutating the object. So, the changes are actually made in the object which has img2.jpg Commented Jun 13, 2014 at 14:08
  • Here's a Fiddle illustrating what @thefourtheye says jsfiddle.net/dMCx3 Note that data in your question is invalid (missing name: in front of 'user2') Commented Jun 13, 2014 at 14:11

1 Answer 1

1

Well your code should already work because _.findWhere returns the first object corresponding to your constraint or undefined if it does not exist, it means that modifying tmpdata.img actually modifies the value you want to modify.

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

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.