Govind Malviya
Govind Malviya

Reputation: 13743

Make array objects all have the same keys

I have a array of object

var arr = 
[
    {"shares":50,"comments":10},
    {"likes":40,"shares":30},
    {"comments":10}
];

I want to convert it to

var arr = 
[
    {"shares":50,"comments":10,"likes":0},
    {"likes":40,"shares":30,"comments":0},
    {"comments":10,"likes":0,"shares":0}
]

Properties are not fixed numbers and names would be different see another example

var arr2 = [{"a":1},{"b":2},{"c":3},{"d":4},{"e":5},{"f":6}]

to

var arr2 = [{"a":1,"b":0,"c":0,"d":0,"e":0,"f":0},{"a":0,"b":1,"c":0,"d":0,"e":0,"f":0},{"a":0,"b":0,"c":1,"d":0,"e":0,"f":0},{"a":0,"b":0,"c":0,"d":1,"e":0,"f":0},{"a":0,"b":0,"c":0,"d":0,"e":1,"f":0},{"a":0,"b":0,"c":0,"d":0,"e":0,"f":1}]

I can do by iterating all elements of array and keys of every element but I don't know that, is it best way?

Is there any inbuilt function in JavaScript or jQuery?

Upvotes: 2

Views: 1117

Answers (5)

Cornchips007
Cornchips007

Reputation: 155

Building on what @dusky said, if you don't actually know what columns will be coming in, you can make a list of columns as a string set. Also assumes you just want to edit the existing array, not make a new one, and use ES6.

    // get all keys added to a list that cannot take duplicates
    const columnNames = new Set<string>();
    arr.forEach(element => {
      Object.keys(element)
        .forEach(x => columnNames.add(x));
    });

    // create default with nulls, can replace with 0 or anything here
    const defaultKeys = {};
    columnNames.forEach(x => {
      defaultKeys[x] = null;
    });

    // Add all missing keys into each object
    arr.forEach((element) => {
      for (const key in defaultKeys) {
        element[key] = element[key] || defaultKeys[key];
      }
    });

Upvotes: 0

pawel
pawel

Reputation: 36965

You can use http://api.jquery.com/jquery.extend/

var defaults = { "shares" : 0, "comments" : 0, "likes" : 0 };

arr = $.map( arr, function( item ){
    return $.extend( {}, defaults, item ); 
});

http://jsfiddle.net/L74q3ksw/

Edit re: updated question

Now it's a matter of building the defaults object which, as I understand, has all the unique keys from all the elements in your array.

So, given

var arr2 = [{"a":1},{"b":2},{"c":3},{"d":4},{"e":5},{"f":6}]

you need to extract "a", "b", "c", "d"... etc and create the defaults.

var defaults = {};
// collect all the keys and set them with value = 0 in defaults
arr2.forEach( function( item ){ 
    Object.keys( item ).forEach( function( key ){
        defaults[ key ] = 0;
    });
});

// same as the previous solution
arr2 = $.map( arr2, function( item ){
        return $.extend( {}, defaults, item ); 
    });

http://jsfiddle.net/7dtfzg2f/2/

Upvotes: 6

dusky
dusky

Reputation: 1313

With pure JavaScript:

var defaults = { "shares": 0, "comments": 0, "likes": 0 };
var arr = [{"shares":50,"comments":10},{"likes":40,"shares":30},{"comments":10}];

arr.slice().map(function(e) {
  for (var key in defaults) {
    e[key] = e[key] || defaults[key];
  }
  return e;
});

This keeps you original array as it was. If you want to change your original array you can do following:

var defaults = { "shares": 0, "comments": 0, "likes": 0 };
var arr = [{"shares":50,"comments":10},{"likes":40,"shares":30},{"comments":10}];

arr.forEach(function(e) {
  for (var key in defaults) {
    e[key] = e[key] || defaults[key];
  }
}); 

You can get the default values from the array with following snippet:

var defaults = arr.reduce(function(m,v) {
 for (var key in v) {
  m[key] = 0;
 }
 return m;
}, {});

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

It looks like you want

var set = {}; // it will be cleaner with ES6 Set
$.each(arr, function(_,e){
     for (var k in e) set[k] = 1;
});
$.each(set, function(k){
    $.each(arr, function(_,e){
        if (e[k]===undefined) e[k] = 0;
    });
});

Demonstration

Upvotes: 1

vaso123
vaso123

Reputation: 12391

Just add the key with value, if it not exists:

$(function() {
    var arr = [{"shares":50,"comments":10},{"likes":40,"shares":30},{"comments":10}];
    $.each(arr, function(idx, obj) {
        if (typeof obj.shares === 'undefined') {
            obj.shares = 0;
        }
        if (typeof obj.comments === 'undefined') {
            obj.comments = 0;
        }
        if (typeof obj.likes === 'undefined') {
            obj.likes = 0;
        }
        arr[idx] = obj;
    });
    console.log(arr);


});

Upvotes: 0

Related Questions