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
381 views
in Technique[技术] by (71.8m points)

Javascript, creating a list and append to it when looping

I need a list in the following Format in Javascript to populate my graph:

    var songs = 
    {
    "Mon": 80,
    "Tues": 40,
    "Wed": 60,
    "Thu": 80,
    "Fri": 40,
    "Sat": 60,
    };

I am getting my data from my API which comes back in a list in the format of:

enter image description here

How can I loop through my list and adapt it to the form of the "songs" list?

Outcome:

var outputList = {
      "19 Jan 2021": 2, 
      "20 Jan 2021" : 5
....
}
question from:https://stackoverflow.com/questions/65904895/javascript-creating-a-list-and-append-to-it-when-looping

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

1 Reply

0 votes
by (71.8m points)

If I understood your problem properly the following should solve it:

let apiResponse = [
  {description: '18 Jan 2021', value: 1},
  {description: '19 Jan 2021', value: 2}
]
let outputList = {};
apiResponse.forEach((row) => {
  outputList[row.description] = row.value;
});
console.log(outputList);

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

...