Skip to content
Advertisement

Mapping in map in json response

I need to parse json api response, with response.data equals:

[
    {
      "name": "Programming",
      "subcategories": [
        {"name": "web-development"},
        {"name": "backend-development"},
        {"name": "data-scince"}
      ]
    },{
      "name": "Design",
      "subcategories": [
        {"name": "Graphic-design"},
        {"name": "Motion-design"},
        {"name": "3D modeling"}
  ]

and I need to return one array[String] with all subcategories, ex [“web-development”, “backend-development” … “3D modeling”]

All that I did is:

let subs = categories.data.map(function(category) {
                    return category.subcategories.map(function(subcategory) {
                        return subcategory.name
                    })
                    })

and it returns Array of arrays with categories. Im sure, that there near a better and easier way. Thanks!

Advertisement

Answer

let data = [{
  "name": "Programming",
  "subcategories": [{
      "name": "web-development"
    },
    {
      "name": "backend-development"
    },
    {
      "name": "data-scince"
    }
  ]
}, {
  "name": "Design",
  "subcategories": [{
      "name": "Graphic-design"
    },
    {
      "name": "Motion-design"
    },
    {
      "name": "3D modeling"
    }
  ]
}]

let subs = data.flatMap(function(category) {
  return category.subcategories.map(function(subcategory) {
    return subcategory.name
  })
})

console.log(subs)

Try using Array flatMap

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement