Skip to content Skip to sidebar Skip to footer

Merge Json-object And Populate Next/prev Items

How can I pre-populate an JSON-Object which contains some css-properties. Where I need to add all not-contained properties to the previous object and the same for all next up items

Solution 1:

This appears to do what you want:

var all = {};

$.each(keyframe, function(_, obj) {
    $.each(obj, function(k) {
        all[k] = 0;
    });
});

$.each(keyframe, function(_, obj) {
    $.each(all, function(k) {
        if(k in obj)
            all[k] = obj[k];
        else
            obj[k] = all[k];
    });
});

console.log(keyframe)
// {"0":{"top":0,"width":0},
// "1000":{"top":100,"width":0},
// "2000":{"width":100,"top":100}}

Solution 2:

Two thoughts:

  1. Create your keyframe objects with a prototype behind them, e.g.:

    varproto= {top:0, width:100};varkeyframe= {
        0:Object.create(proto),  //Inheritseverything1000:Object.create(proto, { //Inheritsonlywidthtop: {value:100}
              },
        2000:Object.create(proto, { //Inheritsonlytopwidth: {value:100}
              })
    };
  2. Do it the manual way, using for-in (spec, article) and in (spec):

    var obj, key;
    for (key in keyframe) {
        obj = keyframe[key];
        if (!('top'in obj)) {
            obj.top = 0;
        }
        if (!('width'in obj)) {
            obj.width = 100;
        }
    }
    

    for-in loops through the names of the enumerable properties of the object. in checks to see if an object as a property with a given name (its own, or on its prototype). In the above, I assumed it was okay for the objects within keyframe to inherit properties.

    If your keyframe objects are every derived from other objects (e.g., they have something other than Object.prototype as their prototype), you'll want to throw a hasOwnProperty in there:

    var obj, key;
    for (key in keyframe) {
        if (keyframe.hasOwnProperty(key)) {
            obj = keyframe[key];
            if (!('top'in obj)) {
                obj.top = 0;
            }
            if (!('width'in obj)) {
                obj.width = 100;
            }
        }
    }
    

Post a Comment for "Merge Json-object And Populate Next/prev Items"