Javascript JS/ES6:如何获取对象数组的特定字段并返回具有特定值的单个对象?

Javascript JS/ES6:如何获取对象数组的特定字段并返回具有特定值的单个对象?,javascript,ecmascript-6,Javascript,Ecmascript 6,有这样一个对象数组: const schema = [ { placeholder: 'Title', name: 'title' }, { placeholder: 'Authors', name: 'author' }, { placeholder: 'Publisher', name: 'publisher', optional: true }, { placeholder: 'Edition', name: 'edition', optional: tr

有这样一个对象数组:

const schema = [
    { placeholder: 'Title', name: 'title' },
    { placeholder: 'Authors', name: 'author' },
    { placeholder: 'Publisher',  name: 'publisher', optional: true },
    { placeholder: 'Edition', name: 'edition', optional: true }
]
现在,我想获得一个对象,其中所有
name
字段都作为键,值为
1
value:

result = { 'title': 1, 'author': 1, 'publisher': 1, 'edition': 1 }
我试图使用
映射
,但是

schema.map(o => { return o.name })
给我一个数组:

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

您需要
reduce

const模式=[
{占位符:'Title',名称:'Title'},
{占位符:'作者',名称:'作者'},
{占位符:'Publisher',名称:'Publisher',可选:true},
{占位符:'Edition',名称:'Edition',可选:true}
]
log(schema.reduce((acc,{name})=>(acc[name]=1,acc),{}))
const模式=[
{占位符:'Title',名称:'Title'},
{占位符:'作者',名称:'作者'},
{占位符:'Publisher',名称:'Publisher',可选:true},
{占位符:'Edition',名称:'Edition',可选:true}
];
console.log(schema.reduce)(acc,current)=>{
acc[当前名称]=1;
返回acc;

}, {}));
.map
将始终为您提供一个数组。由于要将对象数组转换为单个对象,因此使用
.reduce
是有意义的

schema.reduce( (a, c) => {
  a[c.name] = 1;
  return a;
} , {});

您可以先创建一个对象,然后使用
forEach
循环添加属性

const模式=[
{占位符:'Title',名称:'Title'},
{占位符:'作者',名称:'作者'},
{占位符:'Publisher',名称:'Publisher',可选:true},
{占位符:'Edition',名称:'Edition',可选:true}
]
var obj={}
schema.forEach(o=>obj[o.name]=1)

console.log(obj)
您可以使用
对象.assign
和排列语法:

Object.assign(...schema.map(o => ({ [o.name]: 1 })));
const模式=[
{占位符:'Title',名称:'Title'},
{占位符:'作者',名称:'作者'},
{占位符:'Publisher',名称:'Publisher',可选:true},
{占位符:'Edition',名称:'Edition',可选:true}
];
const result=Object.assign(…schema.map(o=>({[o.name]:1}));

控制台日志(结果)最具ESNexty的答案:)@YuryTarabanko,感谢您的欣赏,但严格来说,这只使用ES2015功能(,,)。