I have arrays like this:
const one = [
{id: 1, field1: "a"},
{id: 2, field1: "b"},
{id: 3, field1: "c"},
{id: 4, field1: "d"}
]
const two = [
{id: 4, field2: "4"},
{id: 1, field2: "1"}
]
// what I want to achieve:
const result = [
{id: 1, field1: "a", field2: "1"},
{id: 4, field1: "d", field2: "4"}
]
I want to merge one and two, so I get the result. This is very similar to a SQL join, but I want to do all of this in JavaScript code. Notice:
- This is "joining" by the
id
"column." - The order of the result is the order of the
one
array (sorting by ID is only coincidentally the same order) - Fields from both arrays exist on the result
I've figured out how to do this on my own, but the code is clunky and difficult to read. Basically, you filter over one
and remove elements that don't exist in two
, then you map over one
and merge the fields of the two
array.
Is there a more concise way of achieving this? I'm using lodash, and I was hoping there was a function in there to make this easier, but I haven't found any.