[英]Add new properties of object in lodash
I've two objects and I want to add properties from object A to object B and I try with extend which doesn't work,do I need to use something different ? 我有两个对象,我想添加从对象A到对象B的属性,我尝试使用不起作用的扩展 ,我是否需要使用不同的东西?
a = {
name = "value"
name2 = "value2"
}
b = {
name3 = "value"
name4 = "value2"
}
I want that A will contain both 我希望A包含两者
a = {
name = "value"
name2 = "value2"
name3 = "value"
name4 = "value2"
}
_.extend
(now called _.assign
) is indeed how you do this: _.extend
(现在称为_.assign
)确实是这样做的:
_.assign(a, b);
Live Example : 实例 :
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>" );
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>
First of all, your defined objects are incorrect. 首先,您定义的对象不正确。 Objects must be written as name:value
pairs, separated by a colon (and not by an equality sign). 对象必须写为name:value
对,用冒号 (而不是等号)分隔。 Furthermore, you must use comma separators to delimit the properties of the object, like: 此外,您必须使用逗号分隔符来分隔对象的属性,例如:
var person = {
firstName: "Matthias",
lastName: "Eckhart",
eyeColor: "blue"
};
To extend an object with various properties via lodash , you can use _.assign(object, [sources], [customizer], [thisArg])
: 要通过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>
I believe you want to use the lodash merge
function, rather than extend
. 我相信你想使用lodash merge
函数,而不是extend
。 See: Lodash - difference between .extend() / .assign() and .merge() 请参阅: Lodash - .extend()/ .assign()和.merge()之间的区别
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.