Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS/ES6: How to get specific fields of object array and return a single object with specific value?

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']
like image 522
user3142695 Avatar asked Dec 06 '25 18:12

user3142695


1 Answers

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), {}))
like image 111
Yury Tarabanko Avatar answered Dec 08 '25 09:12

Yury Tarabanko



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!