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?
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 ));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With