Reputation: 337
I have a array like this.
My Array= PartnerNumber,1044,FirstName,rob,Rank,302
I would like it to be represented as key and value pair
[1]Partner Number - 1044
[2]First Name - rob
[3] rank -302
I would need to post this array data and form a query on my server side control.
Thanks in advance
Upvotes: 3
Views: 23228
Reputation: 40639
Try this,
var arr=['PartnerNumber',1044,'FirstName','rob','Rank',302];
var newArr={};
for(var i=0,len=arr.length;i<len;i+=2) {
newArr[arr[i]]=(arr[i+1]);
}
console.log(newArr);
Upvotes: 1
Reputation: 64923
In modern Web browsers, you can use the very useful array.forEach
function:
var array = ["PartnerNumber",1044,"FirstName","rob","Rank",302];
var dictionary = {};
array.forEach(function(item, index) {
if(index % 2 === 0) {
dictionary[item] = array[index + 1];
}
});
document.write("Partner number:" + dictionary.PartnerNumber);
Try it on jsFiddle:
Upvotes: 4
Reputation: 2555
Check this working plunk. Is this what you want? If you open up the console, it will display:
Object { Partner Number: 1044, First Name: "rob", Rank: 302}
EDIT: added code in comment
var myArray = ["PartnerNumber", 1044, "FirstName", "rob", "Rank", 302],
myObj = {};
for (var i = 0; i < myArray.length; i++)
{
if (i % 2 === 0)
myObj[myArray[i].replace(/([A-Z])/g, ' $1').replace(',', '')] = myArray[i + 1];
}
console.log(myObj);
Upvotes: 0
Reputation: 955
obj={};
for(i=0; i<arr.length-1; i=i+2){
obj[arr[i]] = arr[i+1];
}
now if your array is,
arr=[key1,value1,key2,value2,key3,value3];
you will get a new object as,
obj = {key1:value,key2:value2,key3:value3}
;
Upvotes: 0
Reputation: 405
Try this:
var a=["PartnerNumber",1044,"FirstName","rob","Rank",302];
var object={};
for(var i=0;i<a.length;i+=2)
{
object[a[i]]=a[i+1];
}
Then you can access it like,
object["PartnerNumber"]
object["FirstName"]
object["Rank"]
Upvotes: 1