Search code examples
javascriptarraysobjectjavascript-objects

Why object merges properties but array does not merges values


Can someone tell why object merges values but array does not


See the code block below:

const a = {'a': 1, 'b': 2}
const b = {'b': 4, 'c': 3}
console.log({...a, ...b}) 

This Outputs

{ a: 1, b: 4, c: 3 }

But when I use the code below:

const c = [1,2]
const d = [2,3]
console.log([...c, ...d])

This outputs

[ 1, 2, 2, 3 ]

Solution

  • Why object merges properties...

    It doesn't merge properties, it merges objects. Notice the value of b in your result: It's 4 (the value from the b object), not some merged value of 2 (from the a object) and 4 (from the b object). Each property from each source object is just copied into the target object (with later objects overwriting properties from earlier objects), the properties themselves are not merged together.

    But fundamentally, object property spread and iterable spread are just completely different things with different purposes and different semantics, because objects and arrays are different beasts (at least conceptually; arrays actually are objects in JavaScript). Properties have names which are an intrinsic part of the property. Array elements just have indexes, and it's normal for values to be moved around an array (moved to different indexes). The two different definitions of spread are each useful for the data type they're defined for.

    If you want to treat an array like an object, though, you can since arrays are objects in JavaScript. (Although in this case it isn't useful.) Here's an example (I've changed c's element values so it's clear what's coming from where):

    const c = ["a", "b"];
    const d = [2, 3];
    console.log(Object.assign([], c, d));

    In that case, since d has values for both indexes 0 and 1, none of c's elements are in the result. But:

    const c = ["a", "b", "c", "d", "e"];
    const d = [2, 3];
    console.log(Object.assign([], c, d));