Dushyant Bangal Dushyant Bangal - 19 days ago 5
Javascript Question

lodash convert array of objects to single array of keys and multiple array of values

I need to transmit some data, that has too many key-value pairs.
As the keys are similar, I dont want to transmit them with each object.

Consider I have the following data:

[
{
x:11,
y:12
},{
x:21,
y:22
},{
x:31,
y:32
},{
x:41,
y:42
}
];


And I need the final output as

[ [x,y],[[11,12],[21,22],[31,32],[41,42]] ]
OR

[ [x,y],[11,12],[21,22],[31,32],[41,42] ]


On the other end, I should be able to convert back to its original form.
It would be great if it can handle an additional key in some of the objects

I think I have seen lodash or underscore function for something close/similar to this, but I'm not able to find it right now.

NOTE: I don't know what the keys will be

Answer

Lodash v4.17.1

modify original

var modifiedOriginal = _.chain(original)
    .map(_.keys)
    .flatten()
    .uniq()
    .thru(function(header){
        return _.concat(
            [header],
            _.map(original, function(item) {
                return _.chain(item)
                    .defaults(_.zipObject(
                        header, 
                        _.times(_.size(header), _.constant(undefined))
                     ))
                     .pick(header)
                     .values()
                     .value()
            })
         );  
     })
     .value();

modified back to original (keys order is not guarantee)

var backToOriginal = _.map(_.tail(modified), function(item) { 
     return _.chain(_.head(modified))
         .zipObject(item)
         .transform(function(result, val, key) {
             if (!_.isUndefined(val)) {
                 result[key] = val;
             }
          })
          .value();
 });

JSFiddle code https://jsfiddle.net/wa8kaL5g/1/