【问题标题】:Reduce array of json to json object将 json 数组缩减为 json 对象
【发布时间】:2019-09-23 00:43:35
【问题描述】:

我有详细信息

data = {
  name: "charles",
  id: "1",
  education: [
    {"class": "X","marks": 223,"percentage": "59%"},
    {"class": "IX","marks": 223,"percentage": "59%"},
    {"class": "IIX","marks": 223,"percentage": "59%"},
    {"class": "IIIX","marks": 223,"percentage": "59%"}
  ]
}

我想要的结果需要分解成 4 个 json 对象

{name:"charles",id:"1", education:{"class":"X","marks":223,"percentage":59%}}
{name:"charles",id:"1", education:{"class":"IX","marks":223,"percentage":59%}}

谁能告诉我如何实现它?

我成功地循环和创建每个对象,如下所示:

this.data.education.forEach( class => {
        const newData: any = {};
        newData.name= data.name;
        newData.id= data.id;
        newData.education = class ;
array.push(newData);
});

I am looking for any simplist way of achieving it?

【问题讨论】:

  • 问题中没有 JSON,因为 JSON 是一种文本序列化格式。显示的代码是“JavaScript”(和 Object Literal 语法)。请参阅json.org,并适当更新标题/标签/措辞。

标签: arrays json angular


【解决方案1】:

您需要提取 name 和 id 并传递 Education 数组的所有条目。希望这会有所帮助

const data = { name: "charles", id: "1", education: [
    { "class": "X", "marks": 223, "percentage": 59 },
    { "class": "IX", "marks": 223, "percentage": 59 },
    { "class": "IIX", "marks": 223, "percentage": 59 },
    { "class": "IIIX", "marks": 223, "percentage": 59 }
  ]
};
const {name, id} = data;
const response = data.education
  .reduce((result, education) => ([...result, {name, id, education}]), []);

console.log(response)

【讨论】:

    【解决方案2】:
    const newData = data.education
                   .map(e => ({ id: data.id, name: data.name, education: e}))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 2012-07-21
      • 2020-10-02
      • 1970-01-01
      • 2021-09-16
      • 2018-04-16
      相关资源
      最近更新 更多