1

I want to convert array of array into array of key-value pairs using javascript or jquery.

i have array of array like :

var arrOfarr = [[1,'One'],[2,'Two'],[3,'Three']];

how do i convert arrOfarr into the array of key-value pairs that looks like

[{id:1,text:'One'},{id:2,text:'Two'},{id:3,text:'Three'}]

6 Answers 6

6
var result = [];
for (var i = 0, iLength = arrOfarr.length; i < iLength; i++) {
    result.push({ id: arrOfarr[i][0], text: arrOfarr[i][1] });
}

console.log(result);
Sign up to request clarification or add additional context in comments.

Comments

2

you can use $.map()

arrOfarr = jQuery.map(arrOfarr, function(val){
    return {id: val[0], text: val[1]}
})

Demo: Fiddle

5 Comments

not exactly what op was asking for, if you look at his example (resulting objects should always have the properties id and text. At least if I didn't misunderstand.
You dont need jQuery for that, just use Array.prototype.map.
@user1983983 to support IE
I am not sure about browser support for Array#map. As jQuery seems to be already included (according to question tag), I would prefer @ArunPJohny version.
2
var arrOfarr = [[1,'One'],[2,'Two'],[3,'Three']];
var hash = new Array(arrOfarr.length);
for (var x = 0; x < hash.length; x++) {
    hash[x] = {id: arrOfarr[x][0], text: arrOfarr[x][1]};   
}

This might help you with performance if you have a large array or a lot of arrays because it'll allocate the size of the array in advance.

Comments

1
var result = [];
for(var i = 0; i < arrOfarr.length; i++){
    var ar = arrOfarr[i];
    result.push({ id: ar[0], text: ar[1] });
}

Comments

1

You can;

var arr = [[1,'One'],[2,'Two'],[3,'Three']];

var o = []
for (var i = 0; i < arr.length; i++)
{
    o.push({id: arr[i][0], text: arr[i][1]});
}

Comments

1

try this,

a=[[1,'one'],[2,'two'],[3,'three']];
$.each(a,function(id,value){
a[id]={id:value[0],text:value[1]};
});

now a will have three objects as you want.

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.