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

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.