Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hydrate an array of json objects, so that each json with different number of keys shares maximum keys

Tags:

javascript

Is there a javascript library that can transform json like this:

[{},
 {title: ""},
 {title: "", author: "unknown"},
 {isbn: "234234"},
 {author: "n/a"}
]

and returns

[{title:"", author: "", isbn: ""},
 {title: "", author: "", isbn: ""},
 {title: "", author: "unknown", isbn: ""},
 {title: "", author: "", isbn: "234234"},
 {title: "", author: "n/a", isbn: ""}
]

It was a bit difficult to explain this so I am using an easy to understand example.

update: I do not know the property fields ahead of time. It is dynamic.

like image 223
qimisle Avatar asked Nov 21 '25 21:11

qimisle


1 Answers

this one ?

let origin= 
    [ { }
    , { title: '' }
    , { title: '', author: 'unknown' }
    , { isbn: '234234' }
    , { author: 'n/a' }
    ]

const modele = origin.reduce((a,c)=>{
  for(let p in c) if (!a[p]) { a[p]='' }
  return a
},{})

origin.forEach((elm,i)=>origin[i]=Object.assign({}, modele , elm))

// result
origin.forEach(elm=> console.log ( JSON.stringify(elm)))
like image 101
Mister Jojo Avatar answered Nov 23 '25 12:11

Mister Jojo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!