Object.assign And Spread Merge Shallow
Object.assign and spread merge one level deep: overridden keys point to new objects while untouched nested objects stay shared with the source.
Code
// Object.assign 和展开运算符都是浅合并:同名键顶层覆盖,嵌套对象只搬引用
const config = {
timeout: 30,
cache: { ttl: 60 },
};
const patch = { timeout: 60, cache: { ttl: 300 } };
const viaAssign = Object.assign({}, config, patch);
const viaSpread = { ...config, ...patch };
console.log('assign:', viaAssign.timeout, viaAssign.cache.ttl);
console.log('spread:', viaSpread.timeout, viaSpread.cache.ttl);
// 被覆盖的 cache 是新对象:源对象不受影响
console.log('source untouched:', config.cache.ttl);
console.log('distinct nested object:', viaSpread.cache !== config.cache);
// 未被覆盖的嵌套键则共享引用:改副本会穿透到源
const partial = { ...config };
partial.cache.ttl = 120;
console.log('alias write reached source:', config.cache.ttl);Output
Captured from a sandboxed run of this snippet in the build pipeline.
assign: 60 300
spread: 60 300
source untouched: 60
distinct nested object: true
alias write reached source: 120What the code does
Top-level bindings config, patch, viaAssign, viaSpread hold the demo state — nothing sits inside a function scope.
Using it
The run emits 5 labeled sections — assign:, spread:, source untouched:, distinct nested object:, alias write reached source: — one per step.
Key statements
const patch = { timeout: 60, cache: { ttl: 300 } };
const viaAssign = Object.assign({}, config, patch);
const viaSpread = { ...config, ...patch };
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. Its state lives in module-level bindings: `config`, `patch`, `viaAssign`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.