Make array objects all have the same keys

javascript object get value by key
javascript object keys values
object.keys foreach
object to array javascript
javascript map
javascript get value by key in array
javascript key value array
find key in array javascript

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?

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

Array.prototype.keys(), The keys() method returns a new Array Iterator object that contains the keys for each index in the array. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Make array objects all have the same keys. Ask

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/

How to convert an Object {} to an Array [] of key-value pairs in , The ordering of the properties is the same as that given by looping over the property values of the object manually. Syntax: Object.entries(obj). Parameter: obj: It is  Object.keys(obj) Parameters obj The object of which the enumerable's own properties are to be returned. Return value. An array of strings that represent all the enumerable properties of the given object. Description. Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object

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);


});

Object.keys( ) In JavaScript, But JavaScript has objects and constructors which work mostly in the same way to constructors(array and object) and custom constructors(define properties and Object.keys() returns an array of strings that represent all the enumerable  array_keys() returns the keys, numeric and string, from the array. If a search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

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;
}, {});

array_intersect - Manual, array_intersect() returns an array containing all the values of array1 that are you passed the arrays to the function if these keys are relied on later in the script. I couldn't get array_intersect to work with two arrays of identical objects, so I just  Array Elements Can Be Objects. JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array. You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

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];
      }
    });

array_merge - Manual, If the input arrays have the same string keys, then the later value for that key will overwrite to get unique value from multi dimensional array use this instead of functions will function correctly if non-array objects are used as parameters. This will help almost all developers coming to PHP from other dynamic languages. Array; Plain objects also support similar methods, but the syntax is a bit different. Object.keys, values, entries. For plain objects, the following methods are available: Object.keys(obj) – returns an array of keys. Object.values(obj) – returns an array of values. Object.entries(obj) – returns an array of [key, value] pairs.

Object functions · JSONata, Merges an array of objects into a single object containing all the key/value pairs from If any of the input objects contain the same key, then the returned object will contain the The function parameter will get invoked with two arguments:. The every() method checks if all elements in an array pass a test (provided as a function). The every() method executes the function once for each element present in the array: If it finds an array element where the function returns a false value, every() returns false (and does not check the remaining values) If no false occur, every() returns

Objects, Every piece of data is stored in its file by the key. It's easy to find a file get property values of the object: alert ( user . name ) ; // John alert ( user . age ) ; // 30​. The value can In the example above, properties have the same names as variables. Objects are associative arrays with several special features. With all these array and object methods you’ll find you never have to reach for a for or while loop ever again. .filter() Creates a new array based on whether the items of an array pass a certain condition.

Ruby Hashes - A Detailed Guide, All key-value pairs in a hash are surrounded by curly braces {} and comma separated. Hashes can be created As you can see, the result is the same. irb :​002 We'll use the each method again and this time we'll create a new file to test this out. If the data doesn't have a natural label, then typically an array will work fine. callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. If a thisArg parameter is provided to every , it will be used as callback's this value.

Comments
  • He want to add shares, comments and like keys if not exists.
  • @dystroy, I think it's more like adding in the missing key and setting the value to 0.
  • Is this supposed to work only for shares, comments and likes or for any kind of field so that all objects have the same fields?
  • properties are not fixed, name and number would be different.
  • then what is the logic behind that? clarify your question please
  • @GovindKamalaPrakashMalviya See updated code for not fixed properties
  • @PraveenPrasannan "Properties are not fixed numbers and names would be different see another example"
  • @dystroy the question has been edited after I've posted the answer to the original question.
  • this is also solving my problem.