Javascript 如何使用map向对象数组动态添加键值对
我知道这是一个简单的问题,但我不明白为什么我的代码会这样。我正在尝试使用array.map()将属性动态添加到对象数组中。我可以让我的代码以我想要的方式工作并通过测试,但我必须硬编码密钥,这不能使函数灵活/可重用,而且是一种“黑客” 例如:Javascript 如何使用map向对象数组动态添加键值对,javascript,dictionary,Javascript,Dictionary,我知道这是一个简单的问题,但我不明白为什么我的代码会这样。我正在尝试使用array.map()将属性动态添加到对象数组中。我可以让我的代码以我想要的方式工作并通过测试,但我必须硬编码密钥,这不能使函数灵活/可重用,而且是一种“黑客” 例如: // this works but I have to hard code the key 'profession' & not quite how I want it to work function addKeyValue(arr,key,va
// 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 }))
}
请参见,您需要一个
函数addKeyValue(arr,键,值){
返回arr.map((obj)=>({…obj[key]:value}));
}
log(addKeyValue([{name:'Moe'},{name:'Larry'},{name:'Curly'}],'profession','comedian')代码>
作为控制台包装{max height:100%!important;top:0;}
这是否回答了您的问题?