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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With