【问题标题】:Javascript - restructure array of objects according to common valueJavascript - 根据共同值重组对象数组
【发布时间】:2018-03-01 09:47:48
【问题描述】:

我的输入对象数组是这样的,我有一个输入数组是这样的:

[{"id": 657, "name": "Amadeus Basin", "contenttype": "province"}
{"id": 1173, "name": "Amazonas Basin", "contenttype": "province"}
{"id": 373, "name": "American Samoa", "contenttype": "countries"}
{"id": 1, "name": "Samoa", "contenttype": "marine"}
{"id": 796, "name": "Amhara", "contenttype": "province"}]

我想要实现的是:

[
    {
    "contenttype": "province",
    "content" : [
        {
            "id": 657,
            "name": "Amadeus Basin"
        },
        {
            "id": 1173,
            "name": "Amazonas Basin"
        },
        {
            "id": 796,
            "name": "Amhara"
        }
    ]
    }, {

        "contenttype": "countries",
        "content": [
            {
                "id": 373,
                "name" : "American Samoa"
            }
        ]

    },
    {
        "contenttype": "countries",
        "content": [
        {
            "id": 1,
            "name" : "Samoa"
        }
    ]

    }

]

根据一个值拆分数组中的对象,并在这些新创建的对象中创建相同对象的子数组。 使用 lodash 也很好。

【问题讨论】:

  • 加个尝试就好了。
  • 你试过什么?
  • _.groupBy(data, 'contenttype')

标签: javascript arrays lodash


【解决方案1】:

您可以使用reduce 函数遍历每个项目,然后检查它是否存在于数组中,如果没有找到则添加新的,如果找到 - 推入它

const data = [{"id": 657, "name": "Amadeus Basin", "contenttype": "province"},
{"id": 1173, "name": "Amazonas Basin", "contenttype": "province"},
{"id": 373, "name": "American Samoa", "contenttype": "countries"},
{"id": 1, "name": "Samoa", "contenttype": "marine"},
{"id": 796, "name": "Amhara", "contenttype": "province"}];

const grouped = data.reduce((acc, item) => {

  const found = acc.find(i => i.contenttype === item.contenttype);
  const content = {id: item.id, name: item.name};
  
  if(found) {
     found.content.push(content);
  } else {
     acc.push({contenttype: item.contenttype, content: [content] })
  }
  
  return acc;

}, []);

console.log(grouped);

【讨论】:

  • 为什么要投反对票?同意问题没有明确定义....但是....结果似乎正是OP所期望的恕我直言.....
【解决方案2】:

您可以使用_.groupBy 并映射想要的属性。

var data = [{ id: 657, name: "Amadeus Basin", contenttype: "province" }, { id: 1173, name: "Amazonas Basin", contenttype: "province" }, { id: 373, name: "American Samoa", contenttype: "countries" }, { id: 1, name: "Samoa", contenttype: "marine" }, { id: 796, name: "Amhara", contenttype: "province" }],
    result = _(data)
        .groupBy('contenttype')
        .map((value, key) => ({
            contenttype: key,
            content: _.map(value, v => _.pick(v, ['id', 'name']))
        }))
        .value();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

【讨论】:

    猜你喜欢
    • 2012-12-19
    • 2020-04-06
    • 1970-01-01
    • 2017-03-19
    • 2019-10-26
    • 1970-01-01
    • 2020-03-25
    • 2020-04-21
    • 2022-01-02
    相关资源
    最近更新 更多