0

I want to add values to empty object to their correct key that is received dynamically.

Obviously the following does not work because I replace the existing value of that key with the latest value:

let obj = {};

let key;
let value;

key = // from selectors 
value = // from selectors 

obj[key] = value;

How can I "push" the new value to that key instead of replacing it?

For example if value1 and value2 were chosen after 2 iterations with key1 then the end result of the object would be

{"key1": ['value1', 'value2']}
1
  • Just putting it out there - this question has already been answered. You should mark one of them as a solution before all of stackoverflow posts their own solution. Commented Dec 28, 2022 at 12:00

3 Answers 3

3

There are a few ways you can achieve this. A common way is to set obj[key] equal to itself, defaulting it to an empty array with ?? [] (nullish coalescing) if it is null/undefined, ie: nullish), and then using .concat() to return a new array with the added value:

obj[key] = (obj[key] ?? []).concat(value); // ?? can be replaced with `||` for better browser support

Or use ??= (nullish coalescing assignment) to set obj[key] to an empty array if it's nullish, and then push into that array .push() to update the existing array

(obj[key] ??= []).push(value);

The above works because obj[key] ?? = [] will set obj[key] to [] if obj[key] is undefined/null, and then return the reference to the array stored at obj[key], that being the array we just created or the array that already exists at obj[key]. We can then .push() into this array reference which updates it in obj

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

Comments

1

Try this:

if (obj[key] === undefined) obj[key] = []
obj[key].push(value)

Comments

1

When you're assigning, just add to the array or create one if it doesn't exist

obj[key] = [...(obj[key] ?? []), value];

,

obj[key] = (obj[key] ?? []).concat(value);

, or

if (!obj[key]) obj[key] = [];
obj[key].push(value);

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.