将许多键/值对添加到现有JavaScript对象的快捷方式

Short-hand to add many key/value pairs to an existing JavaScript object?

本文关键字:JavaScript 对象 快捷方式 许多键 添加      更新时间:2023-09-26

如果我有一个现有的POJO,并想向其中添加一些键/值对,我通常会这样做:

var existingObject = {
    firstValue: 'hello'
};
/* some time later... */
existingObject.secondValue = 'world';
existingObject.thirdValue = 'new value';
existingObject.fourthValue = 'another value';
existingObject.fifthValue = 'another value';
existingObject.sixthValue = 'another value';
existingObject.seventhValue = 'another value';
existingObject.eighthValue = 'another value';
existingObject.adInfinitum = 'again and again...';

但我想知道是否有比这种长期方法更有效的方法?但是,请注意,我正在寻找创建临时对象和调用extend的替代方案。

此外,简单地将对象存储在较小的变量中(如var a = existingObject;和使用a.newValue = 'something')并不是我想要的解决方案。

有办法做到这一点吗?

使用新的ES6方法Object.assign,可以消除许多重复的样板。示例:

var existingObject = {
    firstValue: 'hello'
};
/* some time later... */
Object.assign(existingObject, {
  secondValue: 'world',
  thirdValue: 'new value',
  fourthValue: 'another value',
  fifthValue: 'another value',
  sixthValue: 'another value',
  seventhValue: 'another value',
  eighthValue: 'another value',
  adInfinitum: 'again and again...'
});
// existingObject now has all these properties

这将在不使用其他临时变量或调用某些外部extend方法的情况下完成。

简短回答:没有。

或者,我能建议的最好的方法是,使用一个可变参数的函数,在键和值之间交替使用。只需将其作为一个空函数,可以选择扩展现有对象。