我有两个对象,我想要将对象A的属性添加到对象B,我尝试使用扩展这不起作用,我是否需要使用不同的东西?
a = {
name = "value"
name2 = "value2"
}
b = {
name3 = "value"
name4 = "value2"
}
我希望A包含两者
a = {
name = "value"
name2 = "value2"
name3 = "value"
name4 = "value2"
}
答案 0 :(得分:26)
_.extend
(现在称为_.assign
)确实是这样做的:
_.assign(a, b);
直播示例:
var a = {
name: "value",
name2: "value2"
};
var b = {
name3: "value",
name4: "value2"
};
_.assign(a, b);
document.body.insertAdjacentHTML(
"beforeend",
"Result:<pre>" + JSON.stringify(a, null, 2) + "</pre>"
);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>
&#13;
答案 1 :(得分:6)
首先,您定义的对象不正确。对象必须写为name:value
对,用冒号(而不是等号)分隔。此外,您必须使用逗号分隔符来分隔对象的属性,例如:
var person = {
firstName: "Matthias",
lastName: "Eckhart",
eyeColor: "blue"
};
要通过lodash扩展具有各种属性的对象,您可以使用_.assign(object, [sources], [customizer], [thisArg])
:
var a = {
name: "value",
name2: "value2"
};
var b = {
name3: "value",
name4: "value2"
};
_.assign(a, b); // extend
console.log(a);
<script src="https://raw.githubusercontent.com/lodash/lodash/3.10.1/lodash.min.js"></script>
答案 2 :(得分:3)
我相信你想使用lodash merge
函数,而不是extend
。请参阅:Lodash - difference between .extend() / .assign() and .merge()