如何使用map动态向对象数组添加键值对

3

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

我知道我可能忽略了一件非常简单的事情,而且也不理解,所以提前感谢大家的帮助!:)


1
这个回答解决了你的问题吗?使用变量作为名称,向JavaScript对象添加属性? - Álvaro Tihanyi
2个回答

4

You need a computed property name.

function addKeyValue(arr,key,value) {
    return arr.map((obj) => ({...obj, [key]: value }));
}

console.log(addKeyValue([{ name: 'Moe' }, { name: 'Larry' }, { name: 'Curly' }], 'profession', 'comedian'));
.as-console-wrapper { max-height: 100% !important; top: 0; }


4
为了在对象字面量中使用表达式作为键名,需要将其放在[]中。
function addKeyValue(arr,key,value) {
    return arr.map((obj) => ({...obj, [key]: value }))
}

请查看创建动态属性名的对象


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接