我知道这是一个简单的问题,但我不明白为什么我的代码会有这样的行为。我正在尝试使用 array.map() 动态地将属性添加到对象数组中。我可以让我的代码按照我想要的方式工作并让我的测试通过,但我必须对 key 进行硬编码,这不会使函数灵活/可重用,并且有点像“黑客”。
示例:
// 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'}]
我知道这可能是一件非常简单的事情,我忽略了,也不理解,所以提前感谢大家的帮助! :)
最佳答案
为了使用表达式作为对象字面量中的键,请将其放入 []
中。
function addKeyValue(arr,key,value) {
return arr.map((obj) => ({...obj, [key]: value }))
}
关于javascript - 如何使用map动态地将键值对添加到对象数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59867455/