2017-08-18 73 views

回答

1

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

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

 
console.log(newObj);

+0

没有真正的解释 - 但第一个正确的答案 - 并加+修复语法。 – sheriffderek

1

几件事情是不正确的

  1. new是一个保留字。你不能用它来在你的temp阵列的项目中声明变量
  2. 缺少括号
  3. 限制了什么,你可以作为一个关键的使用:https://stackoverflow.com/a/6500668/534056

试试这个:

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)