简体   繁体   中英

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!

You can get a flat array by replacing:

categories.data.map

with

categories.data.flatMap

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM