最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Converting an array of objects to Map Immutable.js - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 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./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.

发布评论

评论列表(0)

  1. 暂无评论