gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 11:15:17 25 4
gpt4 key购买 nike

有一个像这样的对象数组:

const schema = [
{ placeholder: 'Title', name: 'title' },
{ placeholder: 'Authors', name: 'author' },
{ placeholder: 'Publisher', name: 'publisher', optional: true },
{ placeholder: 'Edition', name: 'edition', optional: true }
]

现在我想获取一个对象,其中所有 name 字段作为键,具有 1 值:

result = { 'title': 1, 'author': 1, 'publisher': 1, 'edition': 1 }

我尝试使用 map ,但是

schema.map(o => { return o.name })

只给我一个数组:

['title', 'author', 'publisher', 'edition']

最佳答案

您需要减少

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), {}))

关于javascript - JS/ES6 : How to get specific fields of object array and return a single object with specific value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44629828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com