Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have this array of object, within it I have another array of object, how to get:

[
  { id: "5a60626f1d41c80c8d3f8a85" },
  { id: "5a6062661d41c80c8b2f0413" },
  { id: "5a60626f1d41c80c8d3f8a83" },
  { id: "5a60626f1d41c80c8d3f8a84" }
];

From:

[
  {
    id: 1,
    country: [
      {
        id: "5a60626f1d41c80c8d3f8a85"
      },
      {
        id: "5a6062661d41c80c8b2f0413"
      }
    ]
  },
  {
    id: 2,
    country: [
      {
        id: "5a60626f1d41c80c8d3f8a83"
      },
      {
        id: "5a60626f1d41c80c8d3f8a84"
      }
    ]
  }
];

without using a forEach and a temp variable?

When I did:

(data || []).map(o=>{
  return o.country.map(o2=>({id: o2.id}))
})

I got the same structure back.

See Question&Answers more detail:os

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

1 Answer

Latest edit

All modern JS environments now support Array.prototype.flat and Array.prototype.flatMap

const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];

console.log(
  data.flatMap(
    (elem) => elem.country
  )
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...