Cómo concatenar propiedades de múltiples objetos JavaScript


Estoy buscando la mejor manera de "agregar" múltiples objetos JavaScript (matrices asociativas).

Por ejemplo, dado:

a = { "one" : 1, "two" : 2 };
b = { "three" : 3 };
c = { "four" : 4, "five" : 5 };

¿Cuál es la mejor manera de calcular:

{ "one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }
Author: Erik Allik, 2010-03-16

11 answers

ECMAScript 6 introdujo Object.assign() para lograr esto de forma nativa en Javascript.

El Objeto .el método assign() se utiliza para copiar los valores de todas las propiedades propias enumerables de uno o más objetos de origen a un objeto de destino. Devolverá el objeto de destino.

Documentación MDN sobre el objeto.asignar()

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }

Object.assign es compatible con muchos navegadores modernos pero no todos ellos. Utilice un transpiler como Babel y Traceur para generar JavaScript ES5 compatible con versiones anteriores.

 95
Author: filoxo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-24 16:44:12

JQuery tiene una buena manera de hacer esto.

Http://api.jquery.com/jQuery.extend /

 34
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-16 12:39:56

Esto debería hacerlo:

function collect() {
  var ret = {};
  var len = arguments.length;
  for (var i=0; i<len; i++) {
    for (p in arguments[i]) {
      if (arguments[i].hasOwnProperty(p)) {
        ret[p] = arguments[i][p];
      }
    }
  }
  return ret;
}

Entrada:

a = { "one" : 1, "two" : 2 };
b = { "three" : 3 };
c = { "four" : 4, "five" : 5 };
d = collect(a, b, c);
console.log(d);

Salida:

Object one=1 two=2  three=3 four=4 five=5
 32
Author: cletus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-16 13:42:41

Underscore tiene pocos métodos para hacer esto;

1. _.extender (destino, * fuentes)

Copie todas las propiedades de los objetos sourceal objeto destination, y devuelva el objeto destination.

_.extend(a, _.extend(b, c));
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }

O

_.extend(a, b);
=> {"one" : 1, "two" : 2, "three" : 3}
_.extend(a, c);
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }

2. _.defaults (objeto, * defaults)

Rellene propiedades indefinidas en objeto {[12] } con valores de los valores predeterminados y devuelve el objeto .

_.defaults(a, _.defaults(b, c));
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }

O

_.defaults(a, b);
=> {"one" : 1, "two" : 2, "three" : 3}
_.defaults(a, c);
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }
 11
Author: gihanchanuka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-25 09:24:18

ECMAScript 6 tiene operador de propagación . Y ahora puedes hacer esto:

const obj1 = {1: 11, 2: 22}
const obj2 = {3: 33, 4: 44}
const obj3 = {...obj1, ...obj2} 
console.log(obj3)

// {1: 11, 2: 22, 3: 33, 4: 44}
 11
Author: valex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-15 08:16:44

¿Por qué debería restringirse la función a 3 argumentos? Además, compruebe hasOwnProperty.

function Collect() {
    var o={};
    for(var i=0;i<arguments.length;i++) {
      var arg=arguments[i];
      if(typeof arg != "object") continue;
      for(var p in arg) {
        if(arg.hasOwnProperty(p)) o[p] = arg[p];
      }
    }
    return o;
}
 4
Author: Alsciende,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-16 13:55:29
function Collect(a, b, c) {
    for (property in b)
        a[property] = b[property];

    for (property in c)
        a[property] = c[property];

    return a;
}

Aviso: Las propiedades existentes en objetos anteriores se sobrescribirán.

 3
Author: Björn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-16 12:38:37

Probablemente, la forma más rápida, eficiente y genérica es esta (puede combinar cualquier número de objetos e incluso copiar al primero ->asignar):

function object_merge(){
    for (var i=1; i<arguments.length; i++)
       for (var a in arguments[i])
         arguments[0][a] = arguments[i][a];
   return arguments[0];
}

También le permite modificar el primer objeto a medida que pasa por referencia. Si no desea esto, pero desea tener un objeto completamente nuevo que contenga todas las propiedades, entonces puede pasar {} como primer argumento.

var object1={a:1,b:2};
var object2={c:3,d:4};
var object3={d:5,e:6};
var combined_object=object_merge(object1,object2,object3); 

Combined_object y object1 contienen las propiedades de object1, object2, object3.

var object1={a:1,b:2};
var object2={c:3,d:4};
var object3={d:5,e:6};
var combined_object=object_merge({},object1,object2,object3); 

En este caso, combined_object contiene las propiedades de object1,object2,object3 pero object1 no se modifica.

Marque aquí: https://jsfiddle.net/ppwovxey/1 /

Nota: los objetos JavaScript se pasan por referencia.

 1
Author: Selay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-07 01:39:23

Más simple: operadores de propagación

var obj1 = {a: 1}
var obj2 = {b: 2}
var concat = { ...obj1, ...obj2 } // { a: 1, b: 2 }
 1
Author: Rodolfo Paranhos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-30 05:03:40
function collect(a, b, c){
    var d = {};

    for(p in a){
        d[p] = a[p];
    }
    for(p in b){
        d[p] = b[p];
    }
    for(p in c){
        d[p] = c[p];
    }

    return d;
}
 0
Author: Álvaro González,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-16 12:49:08

ES6 ++

La pregunta es agregar varios diferentes objetos en uno.

let obj = {};
const obj1 = { foo: 'bar' };
const obj2 = { bar: 'foo' };
Object.assign(obj, obj1, obj2);
//output => {foo: 'bar', bar: 'foo'};

Digamos que tienes un objeto con varias claves que son objetos:

let obj = {
  foo: { bar: 'foo' },
  bar: { foo: 'bar' }
}

Esta fue la solución que encontré (todavía tengo que foreach:/)

let objAll = {};

Object.values(obj).forEach(o => {
  objAll = {...objAll, ...o};
});

Haciendo esto podemos agregar dinámicamente TODAS las claves de objeto en una.

// Output => { bar: 'foo', foo: 'bar' }
 0
Author: Joseph Briggs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-21 03:40:11