Add new properties of object in lodash

2019-02-09 01:29发布

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 = {
name = "value"
name2 = "value2"
}

b = {
name3 = "value"
name4 = "value2"
}

I want that A will contain both

a = {
name = "value"
name2 = "value2"
name3 = "value"
name4 = "value2"
}

3条回答
劫难
2楼-- · 2019-02-09 02:01

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). 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]):

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>

查看更多
3楼-- · 2019-02-09 02:16

I believe you want to use the lodash merge function, rather than extend. See: Lodash - difference between .extend() / .assign() and .merge()

查看更多
一纸荒年 Trace。
4楼-- · 2019-02-09 02:17

_.extend (now called _.assign) is indeed how you do this:

_.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>

查看更多
登录 后发表回答