javascript - 如何使用map动态地将键值对添加到对象数组中

标签 javascript dictionary

我知道这是一个简单的问题,但我不明白为什么我的代码会有这样的行为。我正在尝试使用 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 }))
}

参见Create an object with dynamic property names

关于javascript - 如何使用map动态地将键值对添加到对象数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59867455/

相关文章:

javascript - 如何获取使用我的具有 iframe 的网络小部件的网站的统计信息?

Java Map迭代使用Map Inside Map并在迭代后将其存储在另一个Map中

javascript - 如何使用 JQuery UI 阻止 UI?

javascript - 在相同高度对齐来自不同父 div 的 div

javascript - 无法更改 iframe 属性

python - 根据列中的相似值创建嵌套字典,并使用值作为字典的键,该字典包含具有该值的所有行

c# - 字典与列表与数组的速度和功能

c++ - 当我尝试使用读取和写入时,为什么 fstream 无法正常工作?

python - 为什么在 self.assertEqual 签名中调用字典键时出现 KeyError ?

javascript - React useReducer 不更新状态