我想返回一個新數組,但將屬性值變成屬性名稱。使用屬性值作爲屬性鍵使用映射
const temp = [
{name: 'james'},
{name: 'ally'}
]
const new = temp.map(obj => ({
`${obj.name}`: null
}))
顯然它不能這樣工作。任何線索? https://jsfiddle.net/qg8ofom1/
我想返回一個新數組,但將屬性值變成屬性名稱。使用屬性值作爲屬性鍵使用映射
const temp = [
{name: 'james'},
{name: 'ally'}
]
const new = temp.map(obj => ({
`${obj.name}`: null
}))
顯然它不能這樣工作。任何線索? https://jsfiddle.net/qg8ofom1/
const temp = [
{name: 'james'},
{name: 'ally'}
];
const newObj = temp.map(obj => ({
[obj.name]: null
}));
console.log(newObj);
沒有真正的解釋 - 但第一個正確的答案 - 並加+修復語法。 – sheriffderek
幾件事情是不正確的
new
是一個保留字。你不能用它來在你的temp
陣列的項目中聲明變量試試這個:
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)
'{[obj.name]:空}' – elclanrs
你能澄清這個問題嗎? – sheriffderek