首页 > 解决方案 > 如何将 JSON 对象保存到多个 JSON 对象 - TypeScript

问题描述

现在我正在formDoc从后端获取 JSON 对象表单数据。

      {
        "components": [
            {
                "label": "Textfield1",
                "type": "textfield",
                "key": "textfield1",
                "input": true
            },
            {   "label": "Radio",
                "type": "radiobutton",
                "key": "radiobutton1",
                "input": true
           },]}

我得到的另一种形式是

       {
"components": [
            {
                "label": "Text2",
                "type": "textfield",
                "key": "textfield2",
                "input": true
            },
            {   "label": "Checkbox",
                "type": "checkbox",
                "key": "checkbox1",
                "input": true
               },
               {   "label": "Checkbox2",
                    "type": "checkbox",
                    "key": "checkbox2",
                    "input": true
               },]}

由于表单是由用户自定义的,因此不同的表单具有不同的组件。我正在尝试按键拆分 JSON。例如,将第一个拆分为

{
                    "label": "Textfield1",
                    "type": "textfield",
                    "key": "textfield1",
                    "input": true
                },

{   "label": "Radio",
                    "type": "radiobutton",
                    "key": "radiobutton1",
                    "input": true
               },

如何在 Typescript 中进行拆分,因为第一个将拆分为两个不同的对象,第二个拆分为三个不同的对象?问题不在于拆分组件,而是如何保存它的任何想法,因为我无法像字符串一样制作“对象”列表。

标签: jsonangulartypescript

解决方案


我不完全明白你的问题,但我理解这两个选项:

//Lets call theObject to your object
const newArray = [];
theObject.forEach(item => item.components.forEach(i => newArray.push(i)));
// now you can do whatever you want with your flat array

如果您有两个不同的对象(在不同的常量/变量中)

const newArray = [...object1.components, ...object2.components];
// now you can do whatever you want with your flat array

推荐阅读