0

I need to flatten an object like this:

{
  ProductId: {
    Id: "123456-1234-1234-1234-123456789012",
    Type: "product",
    Name: "Product"
  }
}

to look like

{
  ProductId_Id: "123456-1234-1234-1234-123456789012",
  ProductId_Type: "product",
  ProductId_Name: "Product"
}

and I'm currently trying to archive that with underscore, but _.flatten doesn't have have a parameter for that.

hinogi
  • 36
  • 3
  • Okay it seems someone got a solution for me already. https://gist.github.com/fantactuka/4989737 – hinogi Jun 03 '14 at 15:30
  • Not an exact duplicate (different flattening of properties, and not underscore-specific), but you might want to have a look at [Fastest way to flatten / un-flatten nested JSON objects](http://stackoverflow.com/q/19098797/1048572) – Bergi Jun 06 '14 at 06:34

1 Answers1

1

You can you .map and .reduce

var raw = {
      ProductId: {
        Id: "123456-1234-1234-1234-123456789012",
        Type: "product",
        Name: "Product"
      }
    },
    flatten = _.map(raw, function(item, k){
       return _.reduce(item, function(obj, val, key){ 
           obj[[k,key].join('_')] = val;
           return obj;
        }, {});
    });
console.log(flatten[0])
Evgeniy
  • 2,915
  • 3
  • 21
  • 35