0

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

works but not able to get proper result. here is the jsfiddle: jsfiddle.net/3gwebtrain/vaeRN/4 can you update here.
@3gwebtrain: Sorry, I got the order of result and item wrong. Edited the answer to reflect the correct order.
1

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"}

6 Comments

Please, don't use for...in with regular array
@Karl-AndréGagnon why so?
@Sprottenwels: If any properties are blindly set on Array.prototype (e.g. to install some kind of polyfill) then you would be iterating over those as well. You don't want that.
@Jon Thank you. So it would be fine if i would do a hasOwnProperty check?
@Karl-AndréGagnon I didn't know about that, thx for your comment. I updated my answer. @Sprottenwels if you're already using underscore.js you should use @Jon answer.
|
0

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"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.