【问题标题】:How to create a new Data Structure from incoming JSON based on specific child Nodes如何根据特定子节点从传入的 JSON 创建新的数据结构
【发布时间】:2020-10-28 21:26:02
【问题描述】:

我有一个如下所示的传入 Json 列表

[{
    "id": 190,
    "title": "This is a Story title",
    "category": [{
        "id": 43,
        "title": "XXX",
        "titleFr": "YYY"
    }, {
        "id": 27,
        "title": "AAA",
        "titleFr": "BBB"
    }]
}, {
    "id": 191,
    "title": "This is a Story title 2",
    "category": [{
        "id": 43,
        "title": "XXX",
        "titleFr": "YYY"
    }]
}]

我希望能够找到所有唯一类别 ID,然后通过按类别分组来创建一个新的数据结构(数组)...即

27 类 - AAA

这是一个故事标题

类别 43 - XXX

这是一个故事标题

这是一个故事标题 2

我有以下代码,到目前为止我可以使用它来遍历并获取类别

$.each(data, function (i, ob) {
    $.each(ob, function (ind, obj) {
        if (ind === "category") {
            Categories.push(this);
        }
    });
});
console.log(Categories);

我觉得上面的方法效率很低,而且它没有考虑到 Category 是否已经存在。

其次,我想我需要再次返回整个列表,查找 Category.Id,找到后创建一个新 obj,然后添加到新列表?

我觉得这里有很多循环,使用 $.each 会非常低效。

任何帮助将不胜感激。

【问题讨论】:

标签: javascript jquery arrays json


【解决方案1】:

您可以使用 vanilla JavaScript 实现此目的,在输入数据上使用 Array.reduce 构建类别列表,迭代每个故事的每个类别并将故事标题推送到类别条目中的数组中。然后您可以使用Object.values 将结果对象转换为数组:

const data = [{
  "id": 190,
  "title": "This is a Story title",
  "category": [{
    "id": 43,
    "title": "XXX",
    "titleFr": "YYY"
  }, {
    "id": 27,
    "title": "AAA",
    "titleFr": "BBB"
  }]
}, {
  "id": 191,
  "title": "This is a Story title 2",
  "category": [{
    "id": 43,
    "title": "XXX",
    "titleFr": "YYY"
  }]
}];

const categories = Object.values(data.reduce((cats, v) => {
  v.category.forEach(c => {
    cats[c.id] = cats[c.id] || {
      id : c.id,
      title : c.title,
      titleFr : c.titleFr,
      stories : []
    };
    cats[c.id].stories.push(v.title);
  });
  return cats;
}, {}));

console.log(categories);

【讨论】:

  • 太棒了,这正是我需要的。我本来希望花一天时间来破解数据,谢谢!
  • @TimCadieux 很酷 - 我不确定输出格式是否适合您的需求,所以我很高兴听到它。
猜你喜欢
  • 2021-10-31
  • 1970-01-01
  • 2018-06-02
  • 2019-05-22
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
相关资源
最近更新 更多