简体   繁体   中英

Array of objects containing objects to flat object array

I'm trying to convert an array of objects containing objects structure to an objects in array structure in JavaScript/Typescript.

Input:

[
  {
    "a": "Content A",
    "b": 
    {
      "1": "Content 1",
      "2": "Content 2"
    }
  },
  {
    "y": "Content Y",
    "x": 
    {
      "3": "Content 3",
      "4": "Content 4"
    }
  },

]

Expected output

[
  {a: "Content A", b: "Content 1"}, 
  {a: "Content A", b: "Content 2"},
  {y: "Content Y", x: "Content 3"},
  {y: "Content Y", x: "Content 4"}
]

Answer with both TS & JS would be awesome!

this should work:

 const all = [ { "a": "Content A", "b": { "1": "Content 1", "2": "Content 2" } }, { "y": "Content Y", "x": { "3": "Content 3", "4": "Content 4" } }, ]; console.log(all.reduce((prev, el) =>{ let curr = Object.entries(el); let k1 = curr[0][0]; let k2 = curr[1][0]; Object.entries(curr[1][1]).forEach((o => { let obj ={} obj[k1] = curr[0][1]; obj[k2] = o[1]; prev.push(obj); })) return prev; },[]))

Use flatMap and Object.entries

 const output = (arr) => arr.flatMap((item) => { const [key1, str] = Object.entries(item).find( ([, val]) => typeof val === "string" ); const [key2, obj] = Object.entries(item).find( ([, val]) => typeof val === "object" ); return Object.values(obj).map((value) => ({ [key1]: str, [key2]: value })); }); const data = [ { a: "Content A", b: { "1": "Content 1", "2": "Content 2", }, }, { y: "Content Y", x: { "3": "Content 3", "4": "Content 4", }, }, ]; console.log(output(data))

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