简体   繁体   中英

how can i map through this array object properly in reactjs?

const demo = [
  {
    a: "message",
    b: "another message",
    c: [{ ab: "inner message", cd: "another inner message" }, { ab: "inner message" ,cd: "another inner message" }],
  },
];

const maping = demo.map((i) => {
  return i.c.map((j)=>{return j.ab});
});
console.log(maping);

All I want to get an array object like this:

[ {ab: "inner message"},{ab: "inner message" } ],

Instead I'm getting:

[ [ {ab: "inner message"},{ab: "inner message" } ] ]

There is some way to get the structure you want:

 const demo = [ { a: "message", b: "another message", c: [{ ab: "inner message", cd: "another inner message" }, { ab: "inner message",cd: "another inner message" }], }, ]; const mapping1 = demo.map(i => { return i.c.map(j => ({ab: j.ab})); }).flat(); console.log("mapping1", mapping1); const mapping2 = demo.reduce((r, i) => { return r.concat(i.c.map(j => ({ab: j.ab}))) }, []); console.log("mapping2", mapping2);

ref:

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