我知道这是一个简单的问题,但我不明白为什么我的代码会有这样的行为。我正在尝试使用array.map()动态向对象数组添加属性。我可以让我的代码按照我想要的方式工作并通过测试,但我必须硬编码键,这使得函数缺乏灵活性和可重用性,并且有点“hacky”。
示例:
// this works but I have to hard code the key 'profession' & not quite how I want it to work
function addKeyValue(arr,key,value) {
return arr.map((obj) => ({...obj, profession: value }))
}
// I don't understand why this doesn't work...
function addKeyValue(arr,key,value) {
return arr.map((obj) => ({...obj, obj[key]: value }))
}
// or this doesn't work either...
function addKeyValue(arr,key,value) {
return arr.map((obj) => ({...obj, obj['key']: value }))
}
// or this...even if I'm already enclosing the key in template strings
// which should effectively set the key as a string which is the reason
// why my first example worked
function addKeyValue(arr,key,value) {
return arr.map((obj) => ({...obj, `${key}`: value }))
}
addKeyValue([{name: 'Moe'}, {name: 'Larry'}, {name: 'Curly'}], 'profession', 'comedian')
// [{name: 'Moe', profession: 'comedian'}, {name: 'Larry', profession: 'comedian'}, {name: 'Curly', profession: 'comedian'}]
我知道我可能忽略了一件非常简单的事情,而且也不理解,所以提前感谢大家的帮助!:)