toaster_fan
toaster_fan

Reputation: 194

merge non matching arrays of objects with ramda

Im trying to merge two arrays of objects based on position with Ramda. Consider that I have the arrays as follows:

const getKeys = [{"name": "id"}, {"name": "temperature"}, {"name": "humidity"}, {"name": "voltage"}, {"name": "upload_time"}]
const getValues = [{data: [1,1,1,1]},{data: [1,2,3,4]},{data: [5,6,7,8]},{data: [1,2,3,4]},{data: [1,2,3,4]}]

I want to end up with:

[{"name": "id", data: [1,1,1,1]}, {"name": "id", data: [1,2,3,4]}, etc...]

So far i have tried it with R.mergeWith but this only merges on matching keys.

Upvotes: 0

Views: 232

Answers (2)

Scott Sauyet
Scott Sauyet

Reputation: 50807

zip and its cousin zipWith are designed for working with arrays that have paired indices. zip would just wrap an array around the two values. zipWith accepts a function and then calls that function with each pair. So, using merge, we can write this as zipWith (merge):

const getKeys = [{"name": "id"}, {"name": "temperature"}, {"name": "humidity"}, {"name": "voltage"}, {"name": "upload_time"}]
const getValues = [{data: [1,1,1,1]},{data: [1,2,3,4]},{data: [5,6,7,8]},{data: [1,2,3,4]},{data: [1,2,3,4]}]

console .log (zipWith (merge) (getKeys, getValues))
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
<script> const {zipWith, merge} = R                                  </script>

Upvotes: 2

izambl
izambl

Reputation: 659

const mergedObject = getKeys.map((keys, index) => ({
   ...keys,
   data: [...getValues[index].data],
}))

this will add the valued to the keys object

Upvotes: 0

Related Questions