如何向 JavaScript 对象添加键/值对?

发布于 2024-07-27 13:45:26 字数 145 浏览 8 评论 0 原文

这是我的对象文字:

var obj = {key1: value1, key2: value2};

如何将带有 value3 的字段 key3 添加到对象?

Here is my object literal:

var obj = {key1: value1, key2: value2};

How can I add field key3 with value3 to the object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

牛↙奶布丁 2024-08-03 13:45:27

您可以使用其中任何一个(假设 key3 是您想要使用的实际密钥),

arr[ 'key3' ] = value3;

或者

arr.key3 = value3;

如果 key3 是一个变量,那么您应该这样做:

var key3 = 'a_key';
var value3 = 3;
arr[ key3 ] = value3;

在此之后,请求 arr.a_key 将返回 < code>value3,文字 3

You could use either of these (provided key3 is the acutal key you want to use)

arr[ 'key3' ] = value3;

or

arr.key3 = value3;

If key3 is a variable, then you should do:

var key3 = 'a_key';
var value3 = 3;
arr[ key3 ] = value3;

After this, requesting arr.a_key would return the value of value3, a literal 3.

忘羡 2024-08-03 13:45:27

今天 2020 年 1 月 14 日性能

我在 Chrome v78.0.0、Safari v13.0.4 和 Firefox v71.0.0 上的 MacOs HighSierra 10.13.6 上对所选解决方案进行了测试。 我将解决方案分为可变(第一个字母 M)和不可变(第一个字母 I)。 我还提供了一些尚未在该问题的答案中发布的不可变解决方案(IB、IC、ID/IE)

结论

  • 最快的可变解决方案比最快的不可变(>10x)
  • 经典可变方法(例如< )快得多code>obj.key3 = "abc" (MA,MB)
  • 对于不可变解决方案 {...obj, key3:'abc'}Object.assign 是最快的 (IA,IB) 速度最快,
  • 令人惊讶的是,不可变的解决方案比 chrome (MC-IA) 和 safari (MD-IB) 的一些可变解决方案更快

在此处输入图像描述

详细信息

在下面的代码片段中,有经过测试的解决方案,您可以在您的计算机上进行测试此处(2022 年更新:我向 Josh DeLong 重写了来自 jspref.com 的测试,该测试不再适用于 jsbench.me)

var o = {
    key1: true,
    key2: 3,
};

var log= (s,f)=> console.log(`${s} --> ${JSON.stringify(f({...o}))}`);



function MA(obj) {
  obj.key3 = "abc";
  return obj;
}

function MB(obj) {
  obj['key3'] = "abc";
  return obj;
}

function MC(obj) {
  Object.assign(obj, {key3:'abc'});
  return obj;
}

function MD(obj) {
  Object.defineProperty(obj, 'key3', {
    value: "abc",       // undefined by default
    enumerable: true,      // false by default
    configurable: true,    // false by default
    writable: true         // false by default
  });
  return obj;
}

function IA(obj) {
  return {...obj, key3:'abc'};
}

function IB(obj) {
  return Object.assign({key3:'abc'}, obj);
}

function IC(obj) {
  let ob= JSON.parse(JSON.stringify(obj))
  ob.key3 = 'abc';
  return ob;
}


function ID(obj) {
    let ob= Object.fromEntries(Object.entries(obj));
  ob.key3 = 'abc';
  return ob;
}

function IE(obj) {
    return Object.fromEntries(Object.entries(obj).concat([['key3','abc']]))
}



log('MA',MA);
log('MB',MB);
log('MC',MC);
log('MD',MD);
log('IA',IA);
log('IB',IB);
log('IC',IC);
log('ID',ID);
log('IE',IE);
This snippet only presents code - it not perform tests itself!

输入图像描述这里

Performance

Today 2020.01.14 I perform tests on MacOs HighSierra 10.13.6 on Chrome v78.0.0, Safari v13.0.4 and Firefox v71.0.0, for chosen solutions. I divide solutions to mutable (first letter M) and immutable (first letter I). I also provide few immutable solutions (IB,IC,ID/IE) not yet published in answers to this question

Conclusions

  • fastest mutable solutions are much faster than fastest immutable (>10x)
  • classic mutable approach like obj.key3 = "abc" (MA,MB) is fastest
  • for immutable solutions the {...obj, key3:'abc'} and Object.assign (IA,IB) are fastest
  • surprisingly there are immutable solutions faster than some mutable solutions for chrome (MC-IA) and safari (MD-IB)

enter image description here

Details

In snippet below there are presended tested solution, you can prefrom test on your machine HERE (update 2022: I send Big thanks to Josh DeLong who rewrite tests from jspref.com which stops working to jsbench.me)

var o = {
    key1: true,
    key2: 3,
};

var log= (s,f)=> console.log(`${s} --> ${JSON.stringify(f({...o}))}`);



function MA(obj) {
  obj.key3 = "abc";
  return obj;
}

function MB(obj) {
  obj['key3'] = "abc";
  return obj;
}

function MC(obj) {
  Object.assign(obj, {key3:'abc'});
  return obj;
}

function MD(obj) {
  Object.defineProperty(obj, 'key3', {
    value: "abc",       // undefined by default
    enumerable: true,      // false by default
    configurable: true,    // false by default
    writable: true         // false by default
  });
  return obj;
}

function IA(obj) {
  return {...obj, key3:'abc'};
}

function IB(obj) {
  return Object.assign({key3:'abc'}, obj);
}

function IC(obj) {
  let ob= JSON.parse(JSON.stringify(obj))
  ob.key3 = 'abc';
  return ob;
}


function ID(obj) {
    let ob= Object.fromEntries(Object.entries(obj));
  ob.key3 = 'abc';
  return ob;
}

function IE(obj) {
    return Object.fromEntries(Object.entries(obj).concat([['key3','abc']]))
}



log('MA',MA);
log('MB',MB);
log('MC',MC);
log('MD',MD);
log('IA',IA);
log('IB',IB);
log('IC',IC);
log('ID',ID);
log('IE',IE);
This snippet only presents code - it not perform tests itself!

enter image description here

寻梦旅人 2024-08-03 13:45:27

展开运算符是一种有用且快速的语法,用于将项目添加到数组、组合数组或对象以及将数组展开到函数的参数中。
现在,ES2018 为对象字面量提供了扩展属性。 它将自己的可枚举属性从提供的对象复制到新对象上。

扩展语法对于将对象的属性和方法组合成一个新对象非常有用:

您可以像这样在对象中添加属性

const obj1 = {hello: "

The spread operator is a useful and quick syntax for adding items to arrays, combining arrays or objects, and spreading an array out into a function’s arguments.
Now, ES2018 comes with spread properties to object literals. It copies its own enumerable properties from a provided object onto a new object.

The spread syntax is useful for combining the properties and methods on objects into a new object:

You can add property in an object like this

const obj1 = {hello: "????"};
const obj2 = {...obj1, laugh: "????" };
console.log('obj1', obj1)
console.log('obj2', obj2)

You can also combine objects like this

const objectOne = {hello: "????"}
const objectTwo = {world: "????"}
const objectThree = {...objectOne, ...objectTwo, laugh: "????"}
console.log(objectThree) // Object { hello: "????", world: "????", laugh: "????" }
const objectFour = {...objectOne, ...objectTwo, laugh: () => {console.log("????".repeat(5))}}
objectFour.laugh() // 

吖咩 2024-08-03 13:45:27
arr.key3 = value3;

因为你的 arr 并不是真正的数组......它是一个原型对象。 真正的数组是:

var arr = [{key1: value1}, {key2: value2}];

但它仍然不正确。 它实际上应该是:

var arr = [{key: key1, value: value1}, {key: key2, value: value2}];
arr.key3 = value3;

because your arr is not really an array... It's a prototype object. The real array would be:

var arr = [{key1: value1}, {key2: value2}];

but it's still not right. It should actually be:

var arr = [{key: key1, value: value1}, {key: key2, value: value2}];
青衫儰鉨ミ守葔 2024-08-03 13:45:27

简单地添加属性:

我们想要添加 prop2 : 2 到这个对象,这些是最方便的选项:

  1. 点运算符:object.prop2 = 2;
  2. 方括号:< code>object['prop2'] = 2;

那么我们使用哪一个呢?

点运算符是更简洁的语法,应该用作默认值(imo)。 但是,点运算符无法向对象添加动态键,这在某些情况下非常有用。 这是一个例子:

const obj = {
  prop1: 1
}

const key = Math.random() > 0.5 ? 'key1' : 'key2';

obj[key] = 'this value has a dynamic key';

console.log(obj);

合并对象:

当我们想要合并两个对象的属性时,这些是最方便的选项:

  1. Object.assign(),将目标对象作为参数,以及一个或多个源对象,然后将合并他们在一起。 例如:
const object1 = {
  a: 1,
  b: 2,
};

const object2 = Object.assign({
  c: 3,
  d: 4
}, object1);

console.log(object2);

  1. 对象扩展运算符 ...
const obj = {
  prop1: 1,
  prop2: 2
}

const newObj = {
  ...obj,
  prop3: 3,
  prop4: 4
}

console.log(newObj);

我们使用哪一个?

  • 扩展语法不太冗长,在我看来应该将其用作默认语法。 不要忘记将此语法转换为所有浏览器都支持的语法,因为它相对较新。
  • Object.assign() 更加动态,因为我们可以访问作为参数传入的所有对象,并且可以在将它们分配给新对象之前对其进行操作。

Simply adding properties:

And we want to add prop2 : 2 to this object, these are the most convenient options:

  1. Dot operator: object.prop2 = 2;
  2. square brackets: object['prop2'] = 2;

So which one do we use then?

The dot operator is more clean syntax and should be used as a default (imo). However, the dot operator is not capable of adding dynamic keys to an object, which can be very useful in some cases. Here is an example:

const obj = {
  prop1: 1
}

const key = Math.random() > 0.5 ? 'key1' : 'key2';

obj[key] = 'this value has a dynamic key';

console.log(obj);

Merging objects:

When we want to merge the properties of 2 objects these are the most convenient options:

  1. Object.assign(), takes a target object as an argument, and one or more source objects and will merge them together. For example:

const object1 = {
  a: 1,
  b: 2,
};

const object2 = Object.assign({
  c: 3,
  d: 4
}, object1);

console.log(object2);

  1. Object spread operator ...

const obj = {
  prop1: 1,
  prop2: 2
}

const newObj = {
  ...obj,
  prop3: 3,
  prop4: 4
}

console.log(newObj);

Which one do we use?

  • The spread syntax is less verbose and has should be used as a default imo. Don't forgot to transpile this syntax to syntax which is supported by all browsers because it is relatively new.
  • Object.assign() is more dynamic because we have access to all objects which are passed in as arguments and can manipulate them before they get assigned to the new Object.
送君千里 2024-08-03 13:45:27

我知道这个问题已经有一个公认的答案,但我想我应该在某个地方记录我的想法。 请[人们]随意在这个想法中找出漏洞,因为我不确定这是否是最好的解决方案......但我只是在几分钟前将其放在一起:

Object.prototype.push = function( key, value ){
   this[ key ] = value;
   return this;
}

您可以这样利用它:

var obj = {key1: value1, key2: value2};
obj.push( "key3", "value3" );

因为,原型函数返回 this 您可以继续将 .push 链接到 obj 变量的末尾: obj.push( ...).push(...).push(...);

另一个功能是您可以传递数组或另一个对象作为推送函数参数中的值。 请参阅我的小提琴的工作示例: http://jsfiddle.net/7tEme/

I know there is already an accepted answer for this but I thought I'd document my idea somewhere. Please [people] feel free to poke holes in this idea, as I'm not sure if it is the best solution... but I just put this together a few minutes ago:

Object.prototype.push = function( key, value ){
   this[ key ] = value;
   return this;
}

You would utilize it in this way:

var obj = {key1: value1, key2: value2};
obj.push( "key3", "value3" );

Since, the prototype function is returning this you can continue to chain .push's to the end of your obj variable: obj.push(...).push(...).push(...);

Another feature is that you can pass an array or another object as the value in the push function arguments. See my fiddle for a working example: http://jsfiddle.net/7tEme/

赢得她心 2024-08-03 13:45:27

大多数答案中已经提到了两种最常用的方法

obj.key3 = "value3";

obj["key3"] = "value3";

定义属性的另一种方法是使用 Object.defineProperty()

Object.defineProperty(obj, 'key3', {
  value: "value3",       // undefined by default
  enumerable: true,      // false by default
  configurable: true,    // false by default
  writable: true         // false by default
});

当您希望在定义属性时拥有更多控制权时,此方法非常有用。
定义的属性可以由用户设置为可枚举、可配置和可写。

Two most used ways already mentioned in most answers

obj.key3 = "value3";

obj["key3"] = "value3";

One more way to define a property is using Object.defineProperty()

Object.defineProperty(obj, 'key3', {
  value: "value3",       // undefined by default
  enumerable: true,      // false by default
  configurable: true,    // false by default
  writable: true         // false by default
});

This method is useful when you want to have more control while defining property.
Property defined can be set as enumerable, configurable and writable by user.

书信已泛黄 2024-08-03 13:45:27

您的示例显示了一个对象,而不是数组。 在这种情况下,向对象添加字段的首选方法是直接分配给它,如下所示:

arr.key3 = value3;

Your example shows an Object, not an Array. In that case, the preferred way to add a field to an Object is to just assign to it, like so:

arr.key3 = value3;
逆夏时光 2024-08-03 13:45:27

我们可以通过多种方式向 JavaScript 对象添加键/值对...

案例 - 1:扩展对象
使用这个我们可以同时向对象添加多个key: value

const rectangle = { width: 4, height: 6 };
const cube = {...rectangle, length: 7};
const cube2 = {...rectangle, length: 7, stroke: 2};
  console.log("Cube2: ", cube2);
  console.log("Cube: ", cube);
  console.log("Rectangle: ", rectangle);

CASE - 2:使用表示法

var rectangle = { width: 4, height: 6 };
rectangle.length = 7;
console.log(rectangle);

CASE - 3:使用[square]表示法

var rectangle = { width: 4, height: 6 };
    rectangle["length"] = 7;
    console.log(rectangle);

We can add a key/value pair to a JavaScript object in many ways...

CASE - 1 : Expanding an object
Using this we can add multiple key: value to the object at the same time.

const rectangle = { width: 4, height: 6 };
const cube = {...rectangle, length: 7};
const cube2 = {...rectangle, length: 7, stroke: 2};
  console.log("Cube2: ", cube2);
  console.log("Cube: ", cube);
  console.log("Rectangle: ", rectangle);

CASE - 2 : Using dot notation

var rectangle = { width: 4, height: 6 };
rectangle.length = 7;
console.log(rectangle);

CASE - 3 : Using [square] notation

var rectangle = { width: 4, height: 6 };
    rectangle["length"] = 7;
    console.log(rectangle);

亣腦蒛氧 2024-08-03 13:45:27

您可以这样添加它:

arr['key3'] = value3;

或这样:

arr.key3 = value3;

建议使用变量 key3 键入对象的答案仅在 key3 的值为 ' 时才有效key3'

You can either add it this way:

arr['key3'] = value3;

or this way:

arr.key3 = value3;

The answers suggesting keying into the object with the variable key3 would only work if the value of key3 was 'key3'.

将军与妓 2024-08-03 13:45:27

下一个 Javascript 规范(候选阶段 3)中的一种简短而优雅的方式是:

obj = { ... obj, ... { key3 : value3 } }

可以在 对象传播与 Object.assign 以及 博士。 阿克塞尔·劳施迈耶斯网站

自 8.6.0 版本以来,它已经在 Node.js 中运行。

最新版本的 Vivaldi、Chrome、Opera 和 Firefox 也知道此功能,但 Mirosoft 直到今天才知道,无论是在 Internet Explorer 中还是在 Edge 中。

A short and elegant way in next Javascript specification (candidate stage 3) is:

obj = { ... obj, ... { key3 : value3 } }

A deeper discussion can be found in Object spread vs Object.assign and on Dr. Axel Rauschmayers site.

It works already in node.js since release 8.6.0.

Vivaldi, Chrome, Opera, and Firefox in up to date releases know this feature also, but Mirosoft don't until today, neither in Internet Explorer nor in Edge.

不喜欢何必死缠烂打 2024-08-03 13:45:27

您可以使用 {[key]: value} 语法创建一个新对象:

const foo = {
  a: 'key',
  b: 'value'
}

const bar = {
  [foo.a]: foo.b
}

console.log(bar); // {key: 'value'}
console.log(bar.key); // value

const baz = {
  ['key2']: 'value2'
}

console.log(baz); // {key2: 'value2'}
console.log(baz.key2); // value2

使用之前的语法,您现在可以使用展开语法 {...foo, ...bar} 来添加新对象,而无需更改旧值:

const foo = {a: 1, b: 2};

const bar = {...foo, ...{['c']: 3}};

console.log(bar); // {a: 1, b: 2, c: 3}
console.log(bar.c); // 3

You can create a new object by using the {[key]: value} syntax:

const foo = {
  a: 'key',
  b: 'value'
}

const bar = {
  [foo.a]: foo.b
}

console.log(bar); // {key: 'value'}
console.log(bar.key); // value

const baz = {
  ['key2']: 'value2'
}

console.log(baz); // {key2: 'value2'}
console.log(baz.key2); // value2

With the previous syntax you can now use the spread syntax {...foo, ...bar} to add a new object without mutating your old value:

const foo = {a: 1, b: 2};

const bar = {...foo, ...{['c']: 3}};

console.log(bar); // {a: 1, b: 2, c: 3}
console.log(bar.c); // 3

黯淡〆 2024-08-03 13:45:27

obj['key3'] = value3obj.key3 = value3 会将新对添加到 obj 中。

但是,我知道 jQuery 没有被提及,但是如果您正在使用它,您可以通过 $.extend(obj,{key3: 'value3'}) 添加对象。 例如:

var obj = {key1: 'value1', key2: 'value2'};
$('#ini').append(JSON.stringify(obj));

$.extend(obj,{key3: 'value3'});

$('#ext').append(JSON.stringify(obj));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="ini">Initial: </p>
<p id="ext">Extended: </p>

jQuery.extend(target[,object1][,objectN]) 合并以下内容两个或多个对象一起构成第一个对象。

它还允许使用 $.extend(true,object1,object2); 进行递归添加/修改:

var object1 = {
  apple: 0,
  banana: { weight: 52, price: 100 },
  cherry: 97
};
var object2 = {
  banana: { price: 200 },
  durian: 100
};
$("#ini").append(JSON.stringify(object1));    

$.extend( true, object1, object2 );
 
$("#ext").append(JSON.stringify(object1));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="ini">Initial: </p>
<p id="ext">Extended: </p>

Either obj['key3'] = value3 or obj.key3 = value3 will add the new pair to the obj.

However, I know jQuery was not mentioned, but if you're using it, you can add the object through $.extend(obj,{key3: 'value3'}). E.g.:

var obj = {key1: 'value1', key2: 'value2'};
$('#ini').append(JSON.stringify(obj));

$.extend(obj,{key3: 'value3'});

$('#ext').append(JSON.stringify(obj));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="ini">Initial: </p>
<p id="ext">Extended: </p>

jQuery.extend(target[,object1][,objectN]) merges the contents of two or more objects together into the first object.

And it also allows recursive adds/modifications with $.extend(true,object1,object2);:

var object1 = {
  apple: 0,
  banana: { weight: 52, price: 100 },
  cherry: 97
};
var object2 = {
  banana: { price: 200 },
  durian: 100
};
$("#ini").append(JSON.stringify(object1));    

$.extend( true, object1, object2 );
 
$("#ext").append(JSON.stringify(object1));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="ini">Initial: </p>
<p id="ext">Extended: </p>

深者入戏 2024-08-03 13:45:27

为了对象前面添加一个键值对,以便 for in 与该元素一起使用,首先执行以下操作:

    var nwrow = {'newkey': 'value' };
    for(var column in row){
        nwrow[column] = row[column];
    }
    row = nwrow;

In order to prepend a key-value pair to an object so the for in works with that element first do this:

    var nwrow = {'newkey': 'value' };
    for(var column in row){
        nwrow[column] = row[column];
    }
    row = nwrow;
陈独秀 2024-08-03 13:45:26

有两种方法可以向对象添加新的属性

var obj = {
    key1: value1,
    key2: value2
};

使用点表示法:

obj.key3 = "value3";

使用方括号表示法:

obj["key3"] = "value3";

当您知道属性名称时,使用第一种形式。 当属性的名称是动态确定的时,使用第二种形式。 就像这个例子一样:

var getProperty = function (propertyName) {
    return obj[propertyName];
};

getProperty("key1");
getProperty("key2");
getProperty("key3");

一个真正的 JavaScript 数组可以使用以下任一方式构造:

数组文字表示法:

var arr = [];

数组构造函数表示法:

var arr = new Array();

There are two ways to add new properties to an object:

var obj = {
    key1: value1,
    key2: value2
};

Using dot notation:

obj.key3 = "value3";

Using square bracket notation:

obj["key3"] = "value3";

The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example:

var getProperty = function (propertyName) {
    return obj[propertyName];
};

getProperty("key1");
getProperty("key2");
getProperty("key3");

A real JavaScript array can be constructed using either:

The Array literal notation:

var arr = [];

The Array constructor notation:

var arr = new Array();
梦在夏天 2024-08-03 13:45:26

2017 年答案:Object.assign()

Object.assign(dest, src1, src2, ...) 合并对象。

它用(无论数量多少)源对象的属性和值覆盖 dest,然后返回 dest

Object.assign() 方法用于将所有可枚举自身属性的值从一个或多个源对象复制到目标对象。 它将返回目标对象。

实例

var obj = {key1: "value1", key2: "value2"};
Object.assign(obj, {key3: "value3"});

document.body.innerHTML = JSON.stringify(obj);

2018 年答案:对象扩展运算符 {...}

obj = {...obj, ...pair, scalar};

来自 MDN

它将自己的可枚举属性从提供的对象复制到新对象。

现在可以使用比Object.assign()

请注意Object.assign () 触发 setters< /a> 而扩展语法则不然。


实例

它适用于当前的 Chrome 和当前的 Firefox。 他们说它在当前的 Edge 中不起作用。

var obj = {key1: "value1", key2: "value2"};
var pair = {key3: "value3"};
var scalar = "value4"
obj = {...obj, ...pair, scalar};

document.body.innerHTML = JSON.stringify(obj);

2019 年答案

对象赋值运算符 +=:

obj += {key3: "value3"};

哎呀...我得意忘形了。 走私未来信息是非法的。 妥妥的遮遮掩掩!

Year 2017 answer: Object.assign()

Object.assign(dest, src1, src2, ...) merges objects.

It overwrites dest with properties and values of (however many) source objects, then returns dest.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Live example

var obj = {key1: "value1", key2: "value2"};
Object.assign(obj, {key3: "value3"});

document.body.innerHTML = JSON.stringify(obj);

Year 2018 answer: object spread operator {...}

obj = {...obj, ...pair, scalar};

From MDN:

It copies own enumerable properties from a provided object onto a new object.

Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().

Note that Object.assign() triggers setters whereas spread syntax doesn’t.

Live example

It works in current Chrome and current Firefox. They say it doesn’t work in current Edge.

var obj = {key1: "value1", key2: "value2"};
var pair = {key3: "value3"};
var scalar = "value4"
obj = {...obj, ...pair, scalar};

document.body.innerHTML = JSON.stringify(obj);

Year 2019 answer

Object assignment operator +=:

obj += {key3: "value3"};

Oops... I got carried away. Smuggling information from the future is illegal. Duly obscured!

A君 2024-08-03 13:45:26

我越来越喜欢 LoDash / 在编写较大项目时使用下划线

通过 obj['key'] 或 obj.key 添加都是可靠的纯 JavaScript 答案。 然而,LoDash 和 Underscore 库在处理一般对象和数组时确实提供了许多额外的方便功能。

.push()适用于数组,不适用于对象

根据您要寻找的内容,有两个特定的函数可能很好用,并且提供类似于 arr.push() 的功能。 有关更多信息,请查看文档,他们有一些很棒的示例。

_.merge (仅限 Lodash)

第二个对象将覆盖或添加到基础对象。
未定义值不会被复制。

var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
_.merge(obj, obj2);
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3"} 

_.extend / _.assign

第二个对象将覆盖或添加到基础对象。
undefined 将被复制。

var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
_.extend(obj, obj2);
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3", key4: undefined}

_.defaults

第二个对象包含默认值,如果它们不存在,则将添加到基础对象中。
如果键已存在,则将复制未定义值。

var obj = {key3: "value3", key5: "value5"};
var obj2 = {key1: "value1", key2:"value2", key3: "valueDefault", key4: "valueDefault", key5: undefined};
_.defaults(obj, obj2);
console.log(obj);
// → {key3: "value3", key5: "value5", key1: "value1", key2: "value2", key4: "valueDefault"}

$.extend

另外,可能值得一提的是 jQuery.extend,它的功能类似于 _ .merge 如果您已经在使用 jQuery,这可能是一个更好的选择。

第二个对象将覆盖或添加到基础对象。
未定义值不会被复制。

var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
$.extend(obj, obj2); 
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3"}

Object.assign()

它可能值得一提的是 ES6/ES2015 Object.assign,它的功能类似于 _.merge,如果你已经在使用像 自己填充

第二个对象将覆盖或添加到基础对象。
undefined 将被复制。

var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
Object.assign(obj, obj2); 
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3", key4: undefined}

I have grown fond of the LoDash / Underscore when writing larger projects.

Adding by obj['key'] or obj.key are all solid pure JavaScript answers. However both of LoDash and Underscore libraries do provide many additional convenient functions when working with Objects and Arrays in general.

.push() is for Arrays, not for objects.

Depending what you are looking for, there are two specific functions that may be nice to utilize and give functionality similar to the the feel of arr.push(). For more info check the docs, they have some great examples there.

_.merge (Lodash only)

The second object will overwrite or add to the base object.
undefined values are not copied.

var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
_.merge(obj, obj2);
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3"} 

_.extend / _.assign

The second object will overwrite or add to the base object.
undefined will be copied.

var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
_.extend(obj, obj2);
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3", key4: undefined}

_.defaults

The second object contains defaults that will be added to base object if they don't exist.
undefined values will be copied if key already exists.

var obj = {key3: "value3", key5: "value5"};
var obj2 = {key1: "value1", key2:"value2", key3: "valueDefault", key4: "valueDefault", key5: undefined};
_.defaults(obj, obj2);
console.log(obj);
// → {key3: "value3", key5: "value5", key1: "value1", key2: "value2", key4: "valueDefault"}

$.extend

In addition, it may be worthwhile mentioning jQuery.extend, it functions similar to _.merge and may be a better option if you already are using jQuery.

The second object will overwrite or add to the base object.
undefined values are not copied.

var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
$.extend(obj, obj2); 
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3"}

Object.assign()

It may be worth mentioning the ES6/ ES2015 Object.assign, it functions similar to _.merge and may be the best option if you already are using an ES6/ES2015 polyfill like Babel if you want to polyfill yourself.

The second object will overwrite or add to the base object.
undefined will be copied.

var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
Object.assign(obj, obj2); 
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3", key4: undefined}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文