我需要能够在运行时合并两个(非常简单的)JavaScript对象.例如,我想:
var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }
obj1.merge(obj2);
//obj1 now has three properties: food, car, and animal
Run Code Online (Sandbox Code Playgroud)
有没有人有这个脚本或知道内置的方法来做到这一点?我不需要递归,我不需要合并函数,只需要平面对象上的方法.
假设我有一个options变量,我想设置一些默认值.
这两种选择的好处/缺点是什么?
使用对象传播
options = {...optionsDefault, ...options};
Run Code Online (Sandbox Code Playgroud)
或者使用Object.assign
options = Object.assign({}, optionsDefault, options);
Run Code Online (Sandbox Code Playgroud)
将两个哈希值合并到%hash1的最佳方法是什么?我总是知道%hash2和%hash1总是有唯一的密钥.如果可能的话,我也更喜欢一行代码.
$hash1{'1'} = 'red';
$hash1{'2'} = 'blue';
$hash2{'3'} = 'green';
$hash2{'4'} = 'yellow';
Run Code Online (Sandbox Code Playgroud)