3gwebtrain
3gwebtrain

Reputation: 15293

How to convert a array containing object string to regular key object pair?

I am trying to convert my uri to object value, as a success level i converted and splited in to array values with colon. But i am not able to onvert those to regular object. any one suggest me a good way. I am suing underscorejs with me.

here is my code :

var ar = ["id:1231", "currency:GBP"];

var outPut = _.map(ar, function(item){
    return '{' + item + '}';
})

console.log(outPut); //consoles as ["{id:1231}", "{currency:GBP}"]

how can i get result like this:

var object = {id:1231, currency:GBP}

is underscore has any in build method for this?

Upvotes: 0

Views: 74

Answers (3)

PeterKA
PeterKA

Reputation: 24638

Here is another version using jQuery:

var newObj = {};
$.each( ar, function( i, v ) {
    var kv = v.split( ":" );
    newObj[ kv[0] ] = kv[ 1 ];
 });
 // newObj = {id:"1231", currency:"GBP"}

Upvotes: 0

Jon
Jon

Reputation: 437336

There are several ways you could go about this, and Underscore offers helpers for them.

One way would be to use _.reduce to incrementally add key/value pairs to an initially empty "result" object:

var obj = _.reduce(ar, function(result, item) {
    var keyAndValue = item.split(":");
    result[keyAndValue[0]] = keyAndValue[1];
    return result;
}, {});

Note that you can do the same without Underscore unless you have to support IE 8 or earlier.

Upvotes: 4

Holt
Holt

Reputation: 37606

Without any third part library:

var output = {} ;
var ar = ["id:1231", "currency:GBP"];
ar.forEach(function (item) {
    var values = item.split(':') ;
    output[values[0]] = values[1] ;
}) ;

Output console.log(output):

Object {id: "1231", currency: "GBP"}

Upvotes: 1

Related Questions