Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace/change item with same key

Using underscore and I have an object array like so -

myObj = [{"car" : "red" },{"tree" : "green"}];

and I am being passed a new object that I need to find and overwrite an object with the same key, so I would be sent like

 {"car" : "blue" };

And I have to take the original object and change the car to blue. Is this possible with underscore? Thanks!

Edit - just to be clear, I am being given the {"car" : "blue"} and I need to compare it to the original object and find the "car" and replace it with the new value. Thanks!

like image 504
ajmajmajma Avatar asked May 02 '26 18:05

ajmajmajma


1 Answers

Sure. Assuming all of your objects only have one key:

var myArr = [ { "car" : "red" }, { "tree": "green" } ];

// First, find out the name of the key you're going to replace
var newObj = { "car": "blue" };
var newObjKey = Object.keys(newObj)[0]; // => "car"

// Next, get the index of the array item that has the key
var index = _.findIndex(myArr, function(obj) { return newObjKey in obj; });
// => 0

// Finally, replace the value
myArr[index][newObjKey] = newObj[newObjKey];

FYI findIndex is an Underscore.js 1.8 feature. If you're using an older version of Underscore, you'll need to replace that line with something like this:

var index;

_.find(myObj, function(obj, idx) {
  if("car" in obj) {
    index = idx;
    return true;
  }
});
like image 177
Jordan Running Avatar answered May 05 '26 08:05

Jordan Running



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!