lundi 29 juin 2015

Reduce in Javascript


So I want to convert:

FROM:
{
    emailNotify: {
        EQ: true
    },
    foo: {
        bar: false
    }
}

TO:

Result : [{'condition': 'EQ', 'attribute': emailNotify, 'value': true}, {'condition': 'bar', 'attribute': foo, 'value': false}]

I tried the following code:

var fromObj={
   emailNotify: {
        EQ: true
    },
    foo: {
        bar: false
    }
};


console.log(Object.keys(fromObj));
var result = (Object.keys(fromObj)).reduce(function(p,c,i,a){
    var newObj={};
    newObj["condition"]=Object.keys(fromObj[c])[0];
    newObj["attribute"]=c;
    newObj["value"]=fromObj[c][Object.keys(fromObj[c])[0]];
    p.push(newObj);
    return p;
},[]);


console.log("result", result);

Is this the way you to would do it as well? I believe I'm not using reduce correctly?!

PS: I get the right result! Just wanted to know if it is the elengant way or not?!


Aucun commentaire:

Enregistrer un commentaire