Raf*_*nix 10 javascript arrays ecmascript-6 lodash
我正在寻找合并一个阵列中所有对象的最佳解决方案
const arrayOfObjects = [
{name: 'Fred', surname: 'Shultz'}, {name: 'Anne', surname: 'Example'}
];
Run Code Online (Sandbox Code Playgroud)
我想实现: {name: ['Fred', 'Anne'], surname: ['Example', 'Shultz']}
什么是最好的选择(es6)?也许我可以用lodash做那样的事情?我应该使用哪些助手?
您可以通过迭代条目并收集值来减少数组,具体取决于键.
const
array = [{ name: 'Fred', surname: 'Shultz' }, { name: 'Anne', surname: 'Example' }],
result = array.reduce((r, o) => {
Object.entries(o).forEach(([k, v]) => (r[k] = r[k] || []).push(v));
return r;
}, Object.create(null));
console.log(result);Run Code Online (Sandbox Code Playgroud)
用lodash很容易:
grouped = _.mapValues(arrayOfObjects[0],
(val, key) => _.map(arrayOfObjects, key))
Run Code Online (Sandbox Code Playgroud)
纯es6
let grouped = {};
for (let obj of arrayOfObjects)
for (let [key, val] of Object.entries(obj))
grouped[key] = (grouped[key] || []).concat(val)
Run Code Online (Sandbox Code Playgroud)
如果按键因项目而异,您可以使用类似的东西来收集它们:
grouped = _(arrayOfObjects)
.flatMap(_.entries)
.groupBy(0)
.mapValues(x => _.map(x, 1))
.value()
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
const arrayOfObjects = [
{name: 'Fred', surname: 'Shultz'}, {name: 'Anne', surname: 'Example'}
];
const result = {};
arrayOfObjects.forEach(item => {
Object.keys(item).forEach(key => {
if (!result[key]) {
result[key] = [];
}
result[key].push(item[key]);
});
});
console.log(result);Run Code Online (Sandbox Code Playgroud)
你可以mergeWith像这样使用lodash :
const result = _.mergeWith({}, ...arrayOfObjects, (value, objValue) =>
(value || []).concat(objValue)
);
Run Code Online (Sandbox Code Playgroud)
例:
const arrayOfObjects = [
{name: 'Fred', surname: 'Shultz'}, {name: 'Anne', surname: 'Example'}
];
const result = _.mergeWith({}, ...arrayOfObjects, (value, objValue) =>
(value || []).concat(objValue)
);
console.log(result);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2059 次 |
| 最近记录: |