Cleanup method to normalize Javascript object properties

I have an array of javascript objects that represent users, for example:

[
  { userName: "Michael",
    city: "Boston"
  },
  { userName: "Thomas",
    state: "California",
    phone: "555-5555"
  },
  { userName: "Kathrine",
    phone: "444-4444"
  }
]

Some objects contain some properties, but not others. I need a clean way to ensure that ALL objects get the same properties. If they do not exist, I want them to have an empty string value, for example:

 [
    { userName: "Michael",
      city: "Boston",
      state: "",
      phone: ""
    },
    { userName: "Thomas",
      city: "",
      state: "California",
      phone: "555-5555"
    },
    { userName: "Kathrine",
      city: "",
      state: "",
      phone: "444-4444"
    }
]

Update I should have been more specific. I was looking for an option that would handle this situation dynamically, so I do not need to know the properties in advance.

For a specific jQuery, the parameter $.extend()is good, but will only work if you know ALL properties ahead of time.

, , , , , , , : 1) JSON, , 900 1000 1 9 . 2) "" , JS, , , .

+3
6

jQuery, $. expand

function Person(options){
    return $.extend({
         userName:"",
         city: "",
         state:"",
         phone: ""
    },options);
}

$.map([{}],Person)

function mapDefaults(arr){
    var defaultProperties = {}
    for(var i =0; i < arr.length; i++){ 
        $.each(arr[i],function(key){
            defaultProperties[key] = "";
        });
    }
    function Defaulter(obj){
        return $.extend({},defaultProperties,obj);
    }
    return $.map(arr, Defaulter);
}

mapDefaults([{a:"valA"},{b:"valB"}]);
/* produces:
 [{a:"valA",b:""},{a:"",b:"valB"}]
*/
+3

-, , :

function coalesceValues(val){
    switch(val)
        case undefined:
        case null:
            return '';
            break;
        default:
            return val;
            break;
    }
}

, :

function coalesceValues(val){
    return val || '';
}

:

var city = coalesceValues(obj.city);

, - - , , , , .

.

+2

, , , , , if , , .

function normalize(object) {
  if(typeof object.userName === 'undefined') {
    object.userName = 'Default Value';
  }
  if(typeof object.city === 'undefined') {
    object.city = 'Default Value';
  }
  if(typeof object.state === 'undefined') {
    object.state = 'Default Value';
  }
  if(typeof object.phone === 'undefined') {
    object.phone = 'Default Value';
  }

  return object;

}

var userArray = [{},{},{}].map(normalize);

.

function User (data) {
  this.userName = data.userName || 'Default Value';
  this.city = data.city || 'Default Value';
  this.state = data.state || 'Default Value';
  this.phone = data.phone || 'Default Value';

 return this;
}

var userArray = [{},{},{}].map(function(o){
 return new User(o);
});

, , , , , , .

+2
source
var list = [
  { userName: "Michael",
    city: "Boston"
  },
  { userName: "Thomas",
    state: "California",
    phone: "555-5555"
  },
  { userName: "Kathrine",
    phone: "444-4444"
  }
];


for(var i = 0; i < list.length; i++){
    if(list[i].state === undefined)
        list[i].state = "";
    if(list[i].phone === undefined)
        list[i].phone = "";
};
 console.log(list); 

http://jsfiddle.net/g5XPk/1/

+1
source

This should probably be a server side task, but ..

If you know all the possible properties ahead of time, you can do this:

http://jsfiddle.net/BMau9/

var properties = ['userName', 'city', 'state', 'phone'];

var data = [{
    userName: "Michael",
    city: "Boston"
}, {
    userName: "Thomas",
    state: "California",
    phone: "555-5555"
}, {
    userName: "Kathrine",
    phone: "444-4444"
}];

for (var i in data) {
    for (var j in properties) {
        data[i][properties[j]] = data[i][properties[j]] || '';
    }
}
0
source

Fiddle This function stores the unique keys of objects in an array, so you can run your array of objects through it, and then use one of the other answers to add keys to objects if they do not exist:

function uniqueKeys(){
    var keys=[];
    function getUniqueKeys(){
        return keys
    }
    function addObject(obj){
        for (var k in obj){
            keys = _.union(keys,[k]);
        }
    }
    return {
        addObj: addObject,
        getKeys: getUniqueKeys
    }
}

Using:

var objArr =  [{ userName: "Michael", city: "Boston"  },
{ userName: "Thomas", state: "California", phone: "555-5555"},
{ userName: "Kathrine",phone: "444-4444" }];

var uniq = new uniqueKeys();
_.each(objArr, function(v){
    uniq.addObj(v)
});
var keys = uniq.getKeys();
alert(keys);
0
source

All Articles