有一个像这样的对象数组:
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']
答案 0 :(得分:4)
您需要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), {}))
答案 1 :(得分:3)
您可以使用Object.assign
和扩展语法:
Object.assign(...schema.map(o => ({ [o.name]: 1 })));
const schema = [
{ placeholder: 'Title', name: 'title' },
{ placeholder: 'Authors', name: 'author' },
{ placeholder: 'Publisher', name: 'publisher', optional: true },
{ placeholder: 'Edition', name: 'edition', optional: true }
];
const result = Object.assign(...schema.map(o => ({ [o.name]: 1 })));
console.log(result);
答案 2 :(得分:2)
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, current) => {
acc[current.name] = 1;
return acc;
}, {}));
答案 3 :(得分:1)
您可以先创建一个对象,然后使用forEach
循环添加属性。
const schema = [
{ placeholder: 'Title', name: 'title' },
{ placeholder: 'Authors', name: 'author' },
{ placeholder: 'Publisher', name: 'publisher', optional: true },
{ placeholder: 'Edition', name: 'edition', optional: true }
]
var obj = {}
schema.forEach(o => obj[o.name] = 1)
console.log(obj)
答案 4 :(得分:0)
.map
将始终为您提供数组。由于您希望将对象数组转换为单个对象,因此使用.reduce
代替它是有意义的。
schema.reduce( (a, c) => {
a[c.name] = 1;
return a;
} , {});