开发者

array spliting based on our requirement

开发者 https://www.devze.com 2023-01-07 17:39 出处:网络
My array contains the values with comma as separator, like array={raju,rani,raghu,siva,stephen,varam}.

My array contains the values with comma as separator, like

array={raju,rani,raghu,siva,stephen,varam}.  

But i want to convert into the below 开发者_如何学JAVAformat like

array = {raju:rani raghu:siva atephen:varam}.

please give some logic to implement this one.


If you're starting with a string, you can split it upon comma:

var myString = 'raju,rani,raghu,siva,stephen,varam';
var array = myString.split(',');

Given that, you can do the following:

var array = [ 'raju', 'rani', 'raghu', 'siva', 'stephen', 'varam' ];
var result = {};

for(var i = 0; i < array.length; i+= 2) {
   result[array[i]] = array[i+1];
}

... which gives the answer you've requested.

Keep in mind that if the array is not evenly divisible by 2, the value of the last item will be undefined.


This is how to convert array to key-value pair of objects (odd-index is key, even-index is value in the resulting key-value pairs)

var array = ['raju', 'rani', 'raghu','siva','stephen','varam'], 
    pairs = {};

for (var i = 0; i < array.length; i += 2) {
    pairs [array[i]] = array[i + 1];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消