0

I am trying to save an API payload to a dictionary. The API data model has the attributes "category", "id" and "name".

let apiPayload = [];

(async () => {
  let fetchValue = await
  fetch('https://asia-southeast1-citric-pager-319712.cloudfunctions.net/gcp-simple-api').then(response => {
    if (response.ok) {
      return response.json();
    }
    throw response;
  }).then(data => {
    return data;
  }).catch(error => console.log(error));

  console.log('fetchValue', fetchValue);

  let dictionary = Object.assign({}, ...fetchValue.map((x) => ({
    [x.category]: [x]
  })));
  console.log('dictionary', dictionary);
})();

How do I append new category object in my dictionary so that it is sorted by category with category objects, e.g.

HTML: [{
  category: "HTML",
  id: "blog-post",
  name: "Blog Post"
}, {...}, {...}],
JavaScript: [{
  category: "JavaScript",
  id: "curry",
  name: "Curry"}, {...}, {...}]
Ryan M
  • 18,333
  • 31
  • 67
  • 74
Adam
  • 33
  • 2
  • 8

1 Answers1

1

Here you go:

async function sample() {
    let categories = {}
    let fetchValue = [] //Array of object, plug your fetch data here

    fetchValue.forEach(e=>{
        if(!categories[e.category]){
            categories[e.category]= [e]
        }else{
            categories[e.category].push(e)
        }
    })
}
Jerry
  • 1,455
  • 1
  • 18
  • 39