动态添加两个json

时间:2018-03-29 14:44:51

标签: javascript arrays json typescript

我有以下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'
            }
        ]
    }
]

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

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

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

1 个答案:

答案 0 :(得分:0)

你可以这样做:

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; }