使用下划线,我有一个像这样的对象数组 -
myObj = [{"car" : "red" },{"tree" : "green"}];
我正在传递一个新对象,我需要用相同的键找到并覆盖一个对象,所以我会像
{"car" : "blue" };
而且我必须拿走原来的对象,把车改成蓝色。这可能带有下划线吗?谢谢!
编辑 - 为了清楚起见,我得到了 {"car": "blue"},我需要将它与原始对象进行比较并找到“car”并将其替换为新值。谢谢!
最佳答案
当然。假设您所有的对象只有一个键:
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
是 Underscore.js 1.8 的一个特性。如果您使用的是旧版本的 Underscore,则需要将该行替换为如下内容:
var index;
_.find(myObj, function(obj, idx) {
if("car" in obj) {
index = idx;
return true;
}
});
关于javascript - 用相同的键替换/更改项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28819510/