使用map将属性值用作属性键

时间:2017-08-18 04:14:13

标签: javascript ecmascript-6

我想返回一个新数组,但是将属性值变为属性名。

const temp = [
  {name: 'james'},
  {name: 'ally'}
]

const new = temp.map(obj => ({
    `${obj.name}`: null
}))

显然它不会这样做。任何线索? https://jsfiddle.net/qg8ofom1/

2 个答案:

答案 0 :(得分:1)

const temp = [
  {name: 'james'},
  {name: 'ally'}
];

const newObj = temp.map(obj => ({
    [obj.name]: null
}));

console.log(newObj);

答案 1 :(得分:1)

有些事情是不正确的

  1. new是保留字。您不能使用它来声明变量
  2. temp数组项目
  3. 周围缺少括号
  4. 仅限于您​​可以使用的密钥:https://stackoverflow.com/a/6500668/534056
  5. 试试这个:

    const temp = [
      { name: 'james' }, 
      { name: 'ally' }
    ]
    
    const newObject = temp.map(obj => ({
      [obj.name]: null
    }))
    
    console.log(newObject)

    那是ES6,所以如果需要,可以使用括号表示法来分配属性

    const temp = [
      { name: 'james' },
      { name: 'ally' }
    ]
    
    const new1 = temp.map(obj => {
      var x = {}
      x[obj.name] = null
      return x
    })
    
    console.log(new1)