Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

javascript - How to change the json response format in angular

I am using Angular 2+ ,

The api json response is like below,

{
 data:[
   {name: "2020-04-28", value: "1", label: "current"}
   {name: "2020-04-28", value: "2", label: "target"}
   {name: "2020-04-29", value: "2", label: "current"}
   {name: "2020-04-29", value: "3", label: "target"}
   {name: "2020-04-30", value: "6", label: "current"}
   {name: "2020-04-30", value: "7", label: "target"}
 ]
}

I have to change above api responce format into,

  {
   data: [
    {
      name: "Current",
      value: [1, 2, 6]
    },
    {
      name: "Target",
      value: [2, 3, 7]
    }
  ]
 }

Can anybody help me to change the format of the json response and please give me the explanation for me to understand the code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It might be naive and non-optimized approach, but it works.

const data = {
    data:[
      {name: "2020-04-28", value: "1", label: "current"},
      {name: "2020-04-28", value: "2", label: "target"},
      {name: "2020-04-29", value: "2", label: "current"},
      {name: "2020-04-29", value: "3", label: "target"},
      {name: "2020-04-30", value: "6", label: "current"},
      {name: "2020-04-30", value: "7", label: "target"}
    ]
   };

let newData = []
data.data.forEach(e => {
    if(newData.length == 0){
        newData.push({
            name: e.label,
            value: [e.value]
        });
    } else {
        let foundIndex = newData.findIndex(fi => fi.name === e.label);
        if(foundIndex >= 0){
            newData[foundIndex].value.push(e.value);
        } else{
            newData.push({
                name: e.label,
                value: [e.value]
            });
        }
        
    }
});
console.log(newData);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...