[英]How can I dynamically add a key value pair to an array of objects using map
I know this is a simple question but I'm not understanding why my code behaves the way it does.我知道这是一个简单的问题,但我不明白为什么我的代码的行为方式如此。 I'm trying to dynamically add a property to an array of objects using array.map().
我正在尝试使用 array.map() 向对象数组动态添加一个属性。 I can get my code to work the way I want to and make my tests pass but I have to hard code the key which doesn't make the function flexible/reusable and is sort of a 'hack'.
我可以让我的代码按照我想要的方式工作并使我的测试通过,但我必须对密钥进行硬编码,这不会使功能变得灵活/可重用,并且有点像“黑客”。
Example:例子:
// 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'}]
I know it's probably a really simple thing I'm overlooking and also not understanding so thanks in advance for everybody's help!我知道这可能是我忽略的一件非常简单的事情,也不理解,所以提前感谢大家的帮助! : )
:)
In order to use an expression as the key in an object literal, put it in []
.为了将表达式用作对象文字中的键,请将其放入
[]
。
function addKeyValue(arr,key,value) {
return arr.map((obj) => ({...obj, [key]: value }))
}
See Create an object with dynamic property names请参见创建具有动态属性名称的对象
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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.