Merging objects (associative arrays)

前端 未结 16 1222
野的像风
野的像风 2020-12-04 08:20

What’s the best/standard way of merging two associative arrays in JavaScript? Does everyone just do it by rolling their own for loop?

16条回答
  •  失恋的感觉
    2020-12-04 08:58

    Now in 2016 I would say the best/standard way is Object.assign()
    Pure Javascript. No jQuery is needed.

    obj1 = {a: 1, b: 2};
    obj2 = {a: 4, c: 110};
    obj3 = Object.assign({},obj1, obj2);  // Object {a: 4, b: 2, c: 110}
    

    More information, examples and polyfill here:
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

提交回复
热议问题