Home > Net >  Add values as array to object key-pair
Add values as array to object key-pair

Time:12-29

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

CodePudding user response:

Try this:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

To add a new value to an existing key in an object, you can use the following syntax:

obj[key].push(value);

This will add the value to the end of the array stored at the key in the obj object.

For example:

let obj = {};

let key = 'key1';
let value1 = 'value1';
let value2 = 'value2';

obj[key] = []; // Initialize the key with an empty array
obj[key].push(value1); // Add value1 to the array at key
obj[key].push(value2); // Add value2 to the array at key

console.log(obj); // Output: { key1: [ 'value1', 'value2' ] }

Note that this will only work if the key already exists in the object and is initialized with an array. If the key does not exist, or if it is initialized with a non-array value, you will need to first create the key and set it to an empty array before you can use the push method.

  • Related