Pregunta

My current collection is as below:

[
  {Tom:true,age:23},
  {Jack:true:age:22},
  {Lucy:false,age:22}
]

How can I convert it into this by underscore?

[
  {name:'Tom',isMale:true,age:23},
  {name:'Jack',isMale:true,age:22},
  {name:'Lucy',isMake:true,age:22}
]
¿Fue útil?

Solución

You could use reduce (the Swiss Army Knife iterator) to copy the inner objects while rearranging the name and isMale values. Something like this:

_(a).map(function(o) {
    return _(o).reduce(function(memo, v, k) {
        if(k === 'age') {
            # Copy 'age' through as-is
            memo[k] = v
        }
        else {
            # Assume the rest is name:boolean so bust it apart
            memo.name   = k;
            memo.isMale = v;
        }
        return memo;
    }, { });
});

Demo: http://jsfiddle.net/ambiguous/FE4Rw/

Otros consejos

Omitting age from your objects and then converting them to pairs could give you a base to work with:

_.map(data, function(o) {
    var p = _.pairs(_.omit(o, 'age'))[0]; // [name, boolean]
    return {
        age: o.age,
        name: p[0],
        isMale: p[1]
    };
});

http://jsfiddle.net/nikoshr/9uE5a/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top