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

时间:2017-06-19 11:50:57

标签: javascript ecmascript-6

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

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']

5 个答案:

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