Cube3
Cube3

Reputation: 121

Converting an array of objects to Map Immutable.js

I have an array of objects which I wish to convert into a plain Immutable map of:

name: {
  urlname
  id
}

Currently I am doing the following data being the array of objects:

data = data.map((data) => ({
  name: data.name,
  urlName: data.urlName,
  id: data.id
}))

What I am trying to transform is the following (data):

[{"id":"10","name":"Dave","urlName":"foo-bar","order":"-100","classId":"12","className":"David","classUrlName":"david-foo-bar"}]

As said above, I would like the name as the key, and both the urlName and the id as values to the key if possible. I would like to loop around data until everything is reduced to that structure if possible.

Upvotes: 3

Views: 6144

Answers (1)

Bamieh
Bamieh

Reputation: 10906

Since you want to transform the data from shape to shape, you can use the reduce function to do this job.

the reduce function will transform the data into a Map where each key is a name, and the values are the id and urlName

const sample = [{"id":"10","name":"Dave","urlName":"foo-bar","order":"-100","classId":"12","className":"David","classUrlName":"david-foo-bar"}];

const result = sample.reduce((acc, item) => {
  return acc.set(item.name, {
     id: item.id,
     urlName: item.urlName,
   })
}, new Immutable.Map())

console.log("Dave's Id", result.getIn(["Dave", "id"]));
console.log("Date's urlName", result.getIn(["Dave", "urlName"]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.9/immutable.js"></script>

Check the documentation here for ImmutableJS Reduce and Native Javascript Array.reduce. Both are identical in their API.

Upvotes: 8

Related Questions