3

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(). 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! : )

tedico
  • 67
  • 5
  • 1
    Does this answer your question? [Add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – Álvaro Tihanyi Jan 22 '20 at 20:09

2 Answers2

4

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392