【问题标题】:Add two json dynamically动态添加两个json
【发布时间】:2018-03-29 14:44:50
【问题描述】:

我有下面显示的jsons:

     json1=
             {
    '201801': 58,
    '201802': 74,
    careerLevel: 'Analyst',
    careerLevels: [{
            '201801': 29,
            '201802': 37,
            careerID: '10000100'
        },
        {
            '201801': 29,
            '201802': 37,
            careerID: '10000110'
        }
    ]
}



     json2 = 
         {
      '201801': 58,
      '201802': 74,
      careerLevel: 'Consultant',
      careerLevels: [{
              '201801': 29,
              '201802': 37,
              careerID: '10000100'
          },
          {
              '201801': 29,
              '201802': 37,
              careerID: '10000110'
          }
      ]
  }

结果我需要动态地合并它们,这样它们应该如下所示:

result=
  careerLevelGroups: [{
        '201801': 58,
        '201802': 74,
        careerLevel: 'Analyst',
        careerLevels: [{
                '201801': 29,
                '201802': 37,
                careerID: '10000100'
            },
            {
                '201801': 29,
                '201802': 37,
                careerID: '10000110'
            }
        ]
    },
    {
        '201801': 58,
        '201802': 74,
        careerLevel: 'Consultant',
        careerLevels: [{
                '201801': 29,
                '201802': 37,
                careerID: '10000100'
            },
            {
                '201801': 29,
                '201802': 37,
                careerID: '10000110'
            }
        ]
    }
]

像上面一样,会有更多相同格式的 json,所以我认为我需要一些循环,我可以直接附加所有这些循环。 我试过了:

jsonMap = new TSMap();
jsonMap.set("careerLevelGroups",[]);
   jsonMap.toJson().concat( json1.concat(json2)); // this is not giving me right answer

我认为我需要一些循环,因为我需要动态添加所有循环。

【问题讨论】:

标签: javascript arrays json typescript


【解决方案1】:

你可以这样做:

const json1 = {'201801': 58,'201802': 74,careerLevel: 'Analyst',careerLevels: [{'201801': 29,'201802': 37,careerID: '10000100'},{'201801': 29,'201802': 37,careerID: '10000110'}]};
const json2 = {'201801': 58,'201802': 74,careerLevel: 'Consultant',careerLevels: [{'201801': 29,'201802': 37,careerID: '10000100'},{'201801': 29,'201802': 37,careerID: '10000110'}]};

const result = {
  careerLevelGroups: [json1, json2]
};

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 谢谢,但你能告诉我这个魔法是如何发生的吗?因为 json 是如何通过逗号分隔来处理的。
  • 你有 json 变量。一种方法是从它们创建一个数组:[json1, json2]
  • 第二个例子是如果你有多个变量json1, json2, ..., json[n],那么你可以迭代并使用eval()方法
猜你喜欢
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-23
  • 1970-01-01
  • 2013-07-16
  • 1970-01-01
  • 2016-08-07
相关资源
最近更新 更多