如果我有一个现有的 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
方法的情况下完成。
关于javascript - 向现有 JavaScript 对象添加许多键/值对的快捷方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25777499/