There is an object array like this:
const schema = [
{ placeholder: 'Title', name: 'title' },
{ placeholder: 'Authors', name: 'author' },
{ placeholder: 'Publisher', name: 'publisher', optional: true },
{ placeholder: 'Edition', name: 'edition', optional: true }
]
Now I would like to get an object with all name fields as key with 1 value:
result = { 'title': 1, 'author': 1, 'publisher': 1, 'edition': 1 }
I tried to use map, but
schema.map(o => { return o.name })
gives me just an array:
['title', 'author', 'publisher', 'edition']
You need reduce
const schema = [
{ placeholder: 'Title', name: 'title' },
{ placeholder: 'Authors', name: 'author' },
{ placeholder: 'Publisher', name: 'publisher', optional: true },
{ placeholder: 'Edition', name: 'edition', optional: true }
]
console.log(schema.reduce((acc, {name}) => (acc[name] = 1, acc), {}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With