【问题标题】:How to convert the JSON into nested Array format in typescript?如何在打字稿中将 JSON 转换为嵌套数组格式?
【发布时间】:2020-11-04 10:31:59
【问题描述】:

我正在尝试将 JSON 转换为嵌套数组格式。以下是我的 JSON 数据:

{
  "items": {
    "BMW": {
      "group": "car",
      "title": "BMW car"
    },
    "320": {
      "group": "BMW",
      "title": "320 Mod"
    },
    "X3": {
      "group": "BMW",
      "title": "X3"
    },
    "X5": {
      "group": "BMW",
      "title": "X5 Mod"
    },
    "Ford": {
      "group": "car",
      "title": "Ford car"
    },
    "Fiesta": {
      "group": "Ford",
      "title": "Fiesta Mod"
    },
    "Focus": {
      "group": "Ford",
      "title": "Focus Mod"
    }
  }
}

JSON 数据有组。基于该组,我需要动态转换为所需的数组格式。下面的数组是我的预期输出。谁能帮我用打字稿写程序。

arrayObj = [
  {
    Name: "BMW car",
    id:"BMW",
    group: "car",
    children: [
      { Name: "320 Mod", id:"320", group: "BMW" },
      { Name: "X3 Mod", id:"X3", group: "BMW" },
      { Name: "X5 Mod", id:"X5", group: "BMW" }
    ]
  },
  {
    Name: "Ford car",
    group: "car",
    id: "Ford",
    children: [
      { Name: "Fiesta Mod", id:"Fiesta", group: "Ford" },
      { Name: "Focus Mod", id:"Focus", group: "Ford" }
    ]
  }
];

【问题讨论】:

标签: arrays json angular typescript


【解决方案1】:

你可以使用reduce()函数来实现这个,见下面的代码

const initialObject = {
  "items": {
    "BMW": {
      "group": "car",
      "title": "BMW"
    },
    "320": {
      "group": "BMW",
      "title": "320"
    },
    "X3": {
      "group": "BMW",
      "title": "X3"
    },
    "X5": {
      "group": "BMW",
      "title": "X5"
    },
    "Ford": {
      "group": "car",
      "title": "Ford"
    },
    "Fiesta": {
      "group": "Ford",
      "title": "Fiesta"
    },
    "Focus": {
      "group": "Ford",
      "title": "Focus"
    }
  }
}
const finalData = Object.values(Object.values(initialObject.items).reduce((prev, {group, title}) => {
  let children = prev[group]?.children
  if (!children) {
    children = []
  }
  children.push({name: title, group })
  return {...prev, [group]: {
    name: group,
    group:title,
    children
  }}
}, {}))


console.log(finalData)

【讨论】:

  • 感谢@Kelvin Owen 的回答。它正在工作,但我得到错误数组 0:{name:“BMW”,组:“X5”,孩子:Array(3)} 1:{name:“car”,组:“Ford”,孩子:Array( 2)} 2: {name: "Ford", group: "Focus", children: Array(2)}
  • 组名错误。我仍在努力。你有什么想法吗??
猜你喜欢
  • 2022-10-14
  • 2021-12-19
  • 2020-12-27
  • 2018-06-14
  • 2018-04-26
  • 2016-09-10
  • 2018-09-18
  • 2018-12-27
  • 1970-01-01
相关资源
最近更新 更多