pileup
pileup

Reputation: 3262

Add values as array to object key-pair

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']}

Upvotes: 0

Views: 84

Answers (3)

Nick Parsons
Nick Parsons

Reputation: 50749

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

Upvotes: 3

Samathingamajig
Samathingamajig

Reputation: 13243

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

Upvotes: 1

no_modules
no_modules

Reputation: 127

Try this:

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

Upvotes: 1

Related Questions