Skip to main content
3 of 10
simplify key check

Array.isArray() could be used instead. That may not be any shorter, but perhaps a better way to determine if the property at key is an array.

var obj={a:1,b:[1,2]}

function add(key,value){
  if(!Array.isArray(obj[key])){
    obj[key]=[obj[key]]
  }
  obj[key].push(value)
}
add('a',3);
console.log(obj);

It would be difficult to prevent the re-assignment of .push:

var obj={a:1,b:[1,2]}

function add(key,value){
  if(!obj[key].push){
    obj[key]=[obj[key]]
  }
  obj[key].push(value)
}
obj.b.push = undefined;
add('b',3);
console.log(obj);

###Edit insertusernamehere pointed out: Perhaps it would be wise to guard against the case where the key does not exist in the object. There are multiple ways to do this, including calling obj.hasOwnProperty(), checking the array returned by Object.keys(obj) does include key, etc.

var obj={a:1,b:[1,2]}

function add(key,value){
  if (!Object.hasOwnProperty(key)) {
      obj[key]=[];
  }
  if(!Array.isArray(obj[key])){
    obj[key]=[obj[key]]
  }
  obj[key].push(value)
}
add('a',3);
add('c',4);
console.log(obj);