Typescript JSON:添加子属性并根据父项属性显示

时间:2018-03-27 16:56:28

标签: json typescript

以下是我需要处理的Json

var oldArr =
[{
"careerLevel": "Associate",
"careerLevels": [
    {
        "201609": 21,
        "201610": 22,
        "careerID": "10000120"
    },
    {
        "201609": 31,
        "201610": 32,
        "careerID": "10000130"
    }]}];

将上面的json转换为:

var newArr= [{
"201609": 52,
"201610": 54,
"careerLevel": "Associate",
"careerLevels": [
    {
        "201609": 21,
        "201610": 22,
        "careerID": "10000120"
    },
    {
        "201609": 31,
        "201610": 32,
        "careerID": "10000130"
    }]

}];

我试图使用reduce()函数实现求和:

var arr = [{x:1},{x:2},{x:4}];

  arr.reduce(function (a, b) {
    return {x: a.x + b.x};
  });

  console.log(arr); //Outputs that same initial array

var reduceArr = oldArr.reduce((sum, item) =>
const total = sum + item.201609; // this gives me error

);

我对减少功能有一些了解,但我对这些东西还是新手。

1 个答案:

答案 0 :(得分:0)

我不知道为什么没人试图这个问题。虽然人们很快就会投票。 我创建了以下代码以获得所需的结果:

 var oldArr =
       {

       "careerLevel": "Associate",
       "careerLevels": [
           {
               "201609": 21,
               "201610": 22,
               "201611": 23,
               "careerID": "10000120"
           },
           {
               "201609": 31,
               "201610": 32,
               "201611": 33,
               "careerID": "10000130"
           }]
   };



   var finalSummedJson = JSON.stringify(SummationProcessing(oldArr));
   return finalSummedJson;


}

// Summation Logic

 function SummationProcessing(oldArr) {
  let sumArr = [];
  let allKeysInLevels = Object.keys(oldArr.careerLevels[0]);
  let uniqueKeys = allKeysInLevels.filter((key, index) => {
      return parseInt(key) > 0 && allKeysInLevels.indexOf(key) == index
  });

  uniqueKeys.forEach(uniqueKey => {
      var sumKey = oldArr.careerLevels.reduce((acc, val) => {
          return acc + val[uniqueKey];
      }, 0);

      sumArr.push(sumKey);
  });

  var reducedData = oldArr.careerLevels.reduce((redArr, inpArr) => {
      var keysToFilter = Object.keys(inpArr);
      var keyysss = keysToFilter.filter((key, index) => { return parseInt(key) > 0 && keysToFilter.indexOf(key) == index });
      keyysss.forEach((element, i) => {
          if (!redArr[element]) {
              redArr[element] = sumArr[i];
          }
          // });
      });
      return redArr;

  }, {});
  // console.log("reducedData", JSON.stringify(reducedData));

  Object.keys(reducedData).forEach(key => { oldArr[key] = reducedData[key] });
  return oldArr;

  // console.log("finalArr", oldArr);
}

最终结果是:

  

{       " 201609":52,       " 201610":54,       " 201611":56,       " careerLevel":" Associate",       " careerLevels":[{           " 201609":21,           " 201610":22,           " 201611":23,           " careerID":" 10000120"       },{           " 201609":31,           " 201610":32,           " 201611":33,           " careerID":" 10000130"       }]   }