Russell Broadbent

Yorkshire based web developer

adding/removing JSON Objects in javascript

I’ve been playing with JSON objects a lot recently and part of a javascript method I was developing required them to be edited. My initial approach for doing this would have been:

var method = {
 datas: {},
 add: function(obj) { 
  var i = this.datas.length; i++;
  this.datas.splice(i, 0, obj);
 },
 remove: function(i) { this.datas.splice(i, 1); }
}

However, for some reason this doesn’t work reliably 100% of the time. So to correct the issue I used jQuery to create a and format a new object, before it was added to the parent object.

var method = {
 datas: {},
 add: function(obj) { 
  var i = this.datas.length; i++;
  var new_obj = $.extend(true, {}, obj);
  this.datas.splice(i, 0, new_obj);
 },
 remove: function(i) { this.datas.splice(i, 1); }
}

Comments are closed.