用相同的键替换/更改项目

Replace/change item with same key

本文关键字:项目 替换      更新时间:2023-09-26

使用下划线和我有一个类似于so-的对象数组

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

并且我被传递了一个新的对象,我需要找到它并用相同的密钥覆盖一个对象,所以我会像一样被发送

 {"car" : "blue" };

我必须把原来的物体换成蓝色。有下划线可以这样做吗?谢谢

编辑-为了清楚起见,我得到了{"车":"蓝色"},我需要将其与原始对象进行比较,找到"车"并用新值替换它。谢谢

当然。假设所有对象只有一个密钥:

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

仅供参考findIndex是Undercore.js 1.8的一个功能。如果你使用的是旧版本的Undercore,你需要用这样的东西来代替它:

var index;
_.find(myObj, function(obj, idx) {
  if("car" in obj) {
    index = idx;
    return true;
  }
});

另一种方法是如下

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] : ''
  }
}

它应该动态替换object2中与数组myObj 中对象中的密钥匹配的任何内容

不需要任何额外的库或疯狂的变量:)只需要好的老式javascript

EDIT在for循环中包含if(object2 && Object.keys(object2)){}之类的内容以确保对象2不是空的/未定义的可能不是一个坏主意