Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript append value to object

There are quite a few similar questions but I couldn't get their answers to work.

 let obj = {};

 const key;//a string
 const value;//a string

 obj[key].push(value);

Obviously this doesn't work but I don't know how to do this. I want it to add a new key and value if it doesn't exist, but if it does exist it should append it to the end of the values for that particular key. ie like the normal push action with arrays.

Expected behaviour:

key = 'hello'
value = 'thanks'

obj = {'hello' : ['thanks']}

key = 'goodbye'
value = 'ok'

obj = {'hello' : ['thanks'], 'goodbye' : ['ok']}

key = 'hello'
value = 'why'

obj = {'hello' : ['thanks','why'], 'goodbye' : ['ok']}

The value 'why' is appended to the end for key 'hello'.

EDIT: All values are put into arrays.

like image 387
Hasen Avatar asked Sep 01 '25 11:09

Hasen


1 Answers

You could create custom function for this that checks if the key exists in object and based on that sets value directly or turns it into an array.

let obj = {
  foo: 'bar'
};

let add = (obj, key, val) => {
  if (key in obj) obj[key] = [].concat(obj[key], val);
  else obj[key] = val;
}

add(obj, 'foo', 'baz');
add(obj, 'bar', 'baz');

console.log(obj)

You could also use Proxy with set trap that will run when you try to set new property on proxy object.

const obj = {
  foo: 'bar'
}

const proxy = new Proxy(obj, {
  set(obj, prop, value) {
    if (prop in obj) obj[prop] = [].concat(obj[prop], value)
    else obj[prop] = value;
  }
})

proxy.foo = 'bar';
proxy.bar = 'baz';
console.log(proxy)
like image 65
Nenad Vracar Avatar answered Sep 03 '25 23:09

Nenad Vracar