Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove default values from an object

Tags:

javascript

I have two javascript objects:

var a = {
    x: 1, 
    y: {
        faz: 'hello', 
        baz: ''
    },
    z: [1, 2]
};


var defaults = {
    x: 2,
    y: {
        faz: '', 
        baz: ''
    },
    z: [1, 2]
};

I want to only keep the fields of a that are different from the default:

a = remove_defaults(a, defaults); // <---- i need this fnc
{
    x: 1,
    y: {
        faz: 'hello'
    }
}

The goal is to remove default values from an object that serves as a state (via URL). The state can have nested fields, so a shallow compare is not enough. The leaf values are all primitive (number, string, bool).

(this is a bit like the opposite of underscore.js's _.defaults() method)

What is the best way to achieve this?


The solution can use underscore.js if that helps, but no jquery.

like image 703
user124114 Avatar asked Jun 13 '12 14:06

user124114


2 Answers

Try this:

function removeDuplicates(a, defaults, result) {
  for (var i in a) {
    if (i in defaults) {
      if (typeof a[i] == "object" 
          && typeof defaults[i] == "object"
          && Object.prototype.toString.call(defaults[i]) !== '[object Array]') {
        result[i] = removeDuplicates(a[i], defaults[i], {});
      } else if (a[i] !== defaults[i]) {
        result[i] = a[i];  
      }
    } else {
      result[i] = a[i];
    }
  }

  return result;
}


var result = removeDuplicates(a, defaults, {});
like image 189
ioseb Avatar answered Oct 02 '22 00:10

ioseb


function remove_defaults(obj, defaults) {
  for (var i in obj) {
    if (typeof obj[i] == 'object') {
      obj[i] = remove_defaults(obj[i], defaults[i]);
      continue;
    }
    if (defaults[i] !== undefined && obj[i] == defaults[i]) {
      delete obj[i];
    }
  }
  return obj;
}

Fiddle: http://jsfiddle.net/ybVGq/

like image 22
jeremyharris Avatar answered Oct 01 '22 23:10

jeremyharris