2

I have an array like this: var arr = ["1:a", "2:b", "3:c"];

From above array I want an object: var obj = { "1": "a", "2": "b", "3": "c" }

I am doing:

  var obj = {}
    $.each(arr, function (i, value) {
        var valueSplit = value.split(':');
// I don't know how to make the object
    });

Edit: My Question is mark as duplicate, while the question I asked is totally opposite of the marked duplicate question.

0

3 Answers 3

2

From your code, in place of the comment you could write

obj[valueSplit[0]] = valueSplit[1];

This could be written as a simple reduce:

var obj = arr.reduce(function(x,y) { return z = y.split(':'), x[z[0]]=z[1], x; }, {});

var arr = ["1:a", "2:b", "3:c"];
var obj = arr.reduce(function(x,y) { return z = y.split(':'), x[z[0]]=z[1], x; }, {});
document.write(JSON.stringify(obj));

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

1 Comment

This would be my preferred approach over using jQuery's $.each.
1

Just add the assignment.

var obj = {}
$.each(arr, function (i, value) {
    var valueSplit = value.split(':');
    obj[valueSplit[0]] = valueSplit[1]; 
});

Comments

0

Simply try this

var arr = ["1:a", "2:b", "3:c"];
var map = {};
arr.forEach( function(val){ 
   var keyVal = val.split( ":" ); 
   map[ keyVal[ 0 ] ] = keyVal[ 1 ];
});

map is the object you are looking for.

DEMO

var arr = ["1:a", "2:b", "3:c"];
var map = {};
arr.forEach( function(val){ 
   var keyVal = val.split( ":" ); 
   map[ keyVal[ 0 ] ] = keyVal[ 1 ];
});

document.body.innerHTML += JSON.stringify( map, 0, 4 );

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.