tedico
tedico

Reputation: 67

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

Upvotes: 3

Views: 2356

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386568

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; }

Upvotes: 4

Barmar
Barmar

Reputation: 780974

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

Upvotes: 4

Related Questions