ajmajmajma
ajmajmajma

Reputation: 14216

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!

Upvotes: 3

Views: 2053

Answers (2)

Jake Boomgaarden
Jake Boomgaarden

Reputation: 3586

another way you can do this would be as follows

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

let object2 = {"car": "blue"}

for(let obj of myObj){
  for(let key in obj){
    object2[key] ? obj[key] = object2[key] : ''
  }
}

That should dynamically replace anything from object2 which matches a key in an object within the array myObj

don't need any extra libraries or crazy variables :) Just good old fashioned javascript

EDIT Might not be a bad idea to include something like if(object2 && Object.keys(object2)){} around the for loop just to ensure that the object2 isn't empty/undefined

Upvotes: 0

Jordan Running
Jordan Running

Reputation: 106027

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

Upvotes: 2

Related Questions