Skip to content

Instantly share code, notes, and snippets.

@tdkn
Created April 11, 2018 16:08
Show Gist options
  • Save tdkn/2de9b4c00b372f9008a406e49df16bbe to your computer and use it in GitHub Desktop.
Save tdkn/2de9b4c00b372f9008a406e49df16bbe to your computer and use it in GitHub Desktop.
Merge complex array of object
[
{
data: [{ x: 1, y: 2 }, { x: 3, y: 4 }]
},
{
data: [{ x: 5, y: 6 }, { x: 7, y: 8 }]
}
].map(({ data }) => data).reduce((acc, cur, i, arr) => {
acc.push(cur.map(({x, y}) => ({ [`x${i}`]: x, [`y${i}`]: y })))
return acc
}, []).reduce((acc, cur, i, arr) => {
if (acc.length > 0) {
cur.forEach((data, index) => acc[index] = { ...acc[index], ...data})
} else {
cur.forEach(data => acc.push(data))
}
return acc
}, [])
@tdkn
Copy link
Author

tdkn commented Apr 11, 2018

[
  {
    "x0": 1,
    "y0": 2,
    "x1": 5,
    "y1": 6
  },
  {
    "x0": 3,
    "y0": 4,
    "x1": 7,
    "y1": 8
  }
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment