2015-06-29 11 views
7

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?

+1

Se quegli oggetti hanno più di una proprietà, non c'è alcuna garanzia che uno si otterrà come proprietà 0. – Pointy

+0

Hanno sempre un proprietà; Odio 'fromObj [c] [Object.keys (fromObj [c]) [0]]' comunque! – user385729

+2

Salva il risultato della chiamata 'Object.keys (fromObj [c]) [0]' invece di chiamarla più volte. Basta aggiungere un altro 'var'. – Pointy

risposta

10

Può essere più semplice con 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));

+1

@pasargad Entrambi gli approcci sono buoni e non vedo qualsiasi preferenza ... –