Javascript 在 lodash 中添加对象的新属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32297542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:51:19  来源:igfitidea点击:

Add new properties of object in lodash

javascriptunderscore.jslodash

提问by 07_05_GuyT

I've two objects and I want to add properties from object A to object B and I try with extendwhich 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"
}

回答by T.J. Crowder

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

回答by Matthias A. Eckhart

First of all, your defined objects are incorrect. Objects must be written as name:valuepairs, separated by a colon(and not by an equality sign). Furthermore, you must use comma separatorsto delimit the properties of the object, like:

首先,您定义的对象不正确。对象必须name:value成对写入,用冒号分隔(而不是等号)。此外,您必须使用逗号分隔符来分隔对象的属性,例如:

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>

回答by jwkicklighter

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

我相信您想使用 lodashmerge函数,而不是extend. 请参阅:Lodash - .extend() / .assign() 和 .merge() 之间的区别