3

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.

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

5 Comments

This is not a map though is it? Is this not an array of maps? When I actually just require a map
@JordanBarber you want to take the map out of the array first?
I would like it to just be a map, so just this: "Dave": { "id": "10", "urlName": "foo-bar" } So that I can do data.getIn(['Dave', 'url'])
@Cube3 glad to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.