是否有实用程序(jquery,lodash等)将一个对象的属性提取到另一个对象,然后从原始对象中删除它们?类似于Array的接头吗?
obj1 = {color:"red", age:"23", name:"cindy"}
obj2 = extract(obj1, ["color","name"])
结果:
obj1 is { age:23 }
obj2 is {color:"red", name:"cindy"}
最佳答案
您可以为此使用一个函数,该函数迭代键并返回一个新的objectc并从源对象中删除键。
function extract(object, keys) {
return keys.reduce(function (o, k) {
o[k] = object[k];
delete object[k];
return o;
}, {});
}
var obj1 = { color: "red", age: "23", name:"cindy" },
obj2 = extract(obj1, ["color","name"]);
console.log(obj1);
console.log(obj2);
关于javascript - 从对象拼接属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42427080/