Aplanar matriz con objetos en 1 objeto
Dado entrada:
[{ a: 1 }, { b: 2 }, { c: 3 }]
Cómo volver:
{ a: 1, b: 2, c: 3 }
Para arrays no es un problema con lodash pero aquí tenemos array de objetos.
5 answers
Uso Object.assign
:
let merged = Object.assign(...arr); // ES6 (2015) syntax
var merged = Object.assign.apply(Object, arr); // ES5 syntax
Tenga en cuenta que Object.assign
aún no está implementado en muchos entornos y es posible que necesite polyfill (ya sea con core-js, otro polyfill o utilizando el polyfill en MDN).
Usted mencionó lodash, por lo que vale la pena señalar que viene con una función _.assign
para este propósito que hace lo mismo:
var merged = _.assign.apply(_, [{ a: 1 }, { b: 2 }, { c: 3 }]);
Pero realmente recomiendo la nueva forma de biblioteca estándar.
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-06-30 11:05:10
Con lodash, puedes usar merge():
var arr = [ { a: 1 }, { b: 2 }, { c: 3 } ];
_.merge.apply(null, [{}].concat(arr));
// → { a: 1, b: 2, c: 3 }
Si estás haciendo esto en varios lugares, puedes hacer merge()
un poco más elegante usando partial () y spread():
var merge = _.spread(_.partial(_.merge, {}));
merge(arr);
// → { a: 1, b: 2, c: 3 }
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-06-30 11:29:10
Aquí hay una versión que no usa métodos ES6...
var arr = [{ a: 1 }, { b: 2 }, { c: 3 }];
var obj = {};
for(var i = 0; i < arr.length; i++) {
var o = arr[i];
for(var key in o) {
if(typeof o[key] != 'function'){
obj[key] = o[key];
}
}
}
console.log(obj);
Violín: http://jsfiddle.net/yaw3wbb8/
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-06-30 11:07:12
Puede usar el subrayado.extender la función así:
var _ = require('underscore');
var a = [{ a: 1 }, { b: 2 }, { c: 3 }];
var result = _.extend.apply(null, a);
console.log(result); // { a: 1, b: 2, c: 3 }
console.log(a); // [ { a: 1, b: 2, c: 3 }, { b: 2 }, { c: 3 } ]
Y para evitar modificar la matriz original debe usar
var _ = require('underscore');
var a = [{ a: 1 }, { b: 2 }, { c: 3 }];
var result = _.extend.apply(null, [{}].concat(a));
console.log(result); // { a: 1, b: 2, c: 3 }
console.log(a); // [ { a: 1 }, { b: 2 }, { c: 3 } ]
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-06-30 11:38:04
Tengo una pequeña solución ordenada que no requiere un polyfill.
var arr = [{ a: 1 }, { b: 2 }, { c: 3 }];
var object = {};
arr.map(function(obj){
var prop = Object.getOwnPropertyNames(obj);
object[prop] = obj[prop];
});
Espero que eso ayude:)
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-06-30 11:23:33