Rename js snippets
This commit is contained in:
45
snippets/js/s/combine-object-arrays.md
Normal file
45
snippets/js/s/combine-object-arrays.md
Normal file
@ -0,0 +1,45 @@
|
||||
---
|
||||
title: Combine object arrays
|
||||
type: snippet
|
||||
language: javascript
|
||||
tags: [array,object]
|
||||
author: chalarangelo
|
||||
cover: digital-nomad-6
|
||||
dateModified: 2020-10-08T02:22:39+03:00
|
||||
---
|
||||
|
||||
Combines two arrays of objects, using the specified key to match objects.
|
||||
|
||||
- Use `Array.prototype.reduce()` with an object accumulator to combine all objects in both arrays based on the given `prop`.
|
||||
- Use `Object.values()` to convert the resulting object to an array and return it.
|
||||
|
||||
```js
|
||||
const combine = (a, b, prop) =>
|
||||
Object.values(
|
||||
[...a, ...b].reduce((acc, v) => {
|
||||
if (v[prop])
|
||||
acc[v[prop]] = acc[v[prop]]
|
||||
? { ...acc[v[prop]], ...v }
|
||||
: { ...v };
|
||||
return acc;
|
||||
}, {})
|
||||
);
|
||||
```
|
||||
|
||||
```js
|
||||
const x = [
|
||||
{ id: 1, name: 'John' },
|
||||
{ id: 2, name: 'Maria' }
|
||||
];
|
||||
const y = [
|
||||
{ id: 1, age: 28 },
|
||||
{ id: 3, age: 26 },
|
||||
{ age: 3}
|
||||
];
|
||||
combine(x, y, 'id');
|
||||
// [
|
||||
// { id: 1, name: 'John', age: 28 },
|
||||
// { id: 2, name: 'Maria' },
|
||||
// { id: 3, age: 26 }
|
||||
// ]
|
||||
```
|
||||
Reference in New Issue
Block a user