Yordan Kanchelov
Yordan Kanchelov

Reputation: 581

convert array into object using underscore only

I am learning underscore now and found a task for it I need help with .. I have an array with object looking like this

[
    // ...
    {
            "type": "presence",
            "params": {
                "interval": 15,
                "foo": "something",
                "link": {
                    "fp_type": "1",
                    "fp_ext_id": "2"
            },
    },
    {
            "type": "bar",
            "params": {
                "interval": 30,
                "foo": "foo",
                "link": {
                    "fp_type": "2",
                    "fp_ext_id": "3"
                },
            },
    },
    // ...
]

The task is using underscore only to convert this array items to an object where the the key is the items type and the value are its params, i.e.:

{
  // ...
  "presence": {
    "interval": 15,
    "foo": "something",
    "link": {
        "fp_type": "1",
        "fp_ext_id": "2"
     },
  }, 
  "bar": {
       "interval": 30,
       "foo": "foo",
       "link": {
           "fp_type": "2",
           "fp_ext_id": "3"
       },
  // ...
}

Upvotes: 0

Views: 606

Answers (1)

hd84335
hd84335

Reputation: 9883

You can do it this way:

var x = [    
    {
            "type": "presence",
            "params": {
                "interval": 15,
                "foo": "something",
                "link": {
                    "fp_type": "sponsor",
                    "fp_ext_id": "spotme"
                },
            },
    },
    {
            "type": "bar",
            "params": {
                "interval": 30,
                "foo": "foo",
                "link": {
                    "fp_type": "2",
                    "fp_ext_id": "3"
                },
            },
    }
];

var y = _.map(x, function(i) {
  let obj = {};
  obj[i.type] = i.params;
  return obj;
});
//console.log(y);

var result = y.reduce(function(obj,item) {	
  obj[_.keys(item)[0]] = _.values(item)[0]; 
  return obj;
}, {});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

DEMO

Upvotes: 2

Related Questions