quindi voglio convertire:Ridurre in Javascript
Da:
{
emailNotify: {
EQ: true
},
foo: {
bar: false
}
}
Per:
[
{'condition': 'EQ', 'attribute': emailNotify, 'value': true},
{'condition': 'bar', 'attribute': foo, 'value': false}
]
ho provato il seguente codice:
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);
È così che faresti anche tu? Credo che non sto usando riduci correttamente?
PS: ottengo il risultato giusto! Volevo solo sapere se è il modo migliore o no?
Se quegli oggetti hanno più di una proprietà, non c'è alcuna garanzia che uno si otterrà come proprietà 0. – Pointy
Hanno sempre un proprietà; Odio 'fromObj [c] [Object.keys (fromObj [c]) [0]]' comunque! – user385729
Salva il risultato della chiamata 'Object.keys (fromObj [c]) [0]' invece di chiamarla più volte. Basta aggiungere un altro 'var'. – Pointy