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.
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.
Share Improve this question edited Nov 23, 2017 at 17:29 Cube3 asked Nov 23, 2017 at 17:22 Cube3Cube3 1212 silver badges11 bronze badges1 Answer
Reset to default 8Since 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./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.