Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce in Javascript

So I want to convert:

From:

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

To:

[
  {'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?

like image 834
user385729 Avatar asked Jun 29 '15 19:06

user385729


1 Answers

It can be simpler with Array.prototype.map:

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

var result = Object.keys(fromObj).map(function(key) {
    var subObj = Object.keys(fromObj[key]);
    return {
        condition: subObj[0],
        attribute: key,
        value: fromObj[key][subObj[0]]
    };
});

alert(JSON.stringify( result, null, 4 ));
like image 50
dfsq Avatar answered Oct 05 '22 19:10

dfsq