使用属性值作为属性键使用映射

问题描述:

我想返回一个新数组,但将属性值变成属性名称。使用属性值作为属性键使用映射

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

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

显然它不能这样工作。任何线索? https://jsfiddle.net/qg8ofom1/

+3

'{[obj.name]:空}' – elclanrs

+0

你能澄清这个问题吗? – sheriffderek

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

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

 
console.log(newObj);

+0

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

几件事情是不正确的

  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)