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.
My own take:
Note this deep-processes objects, but not arrays. Arrays are only processed for shallow difference of their direct elements — if the elements themselves need
no_defaulting, this function won’t do. But this is fine for my intended use case.