Reputation: 107
Little bit of different format of array.
var string = "A,B,C,D";
Output should be:
drp1: {A:-1,B:-2,C:-3,D:-4}
I cannot figure out how to get such format with JavaScipt.
Upvotes: 0
Views: 57
Reputation: 122986
You could use Array.map
(see MDN)
var obj = {};
'A,B,C,D'.split(',').map(function (v, i) {this[a] = -(i+1);}, obj);
Upvotes: 0
Reputation: 149078
The simple solution would be to use split
to convert your string to an array, then use reduce
to construct the object in the form you want:
var string = "A,B,C,D"
var drp1 = string.split(',').reduce(function(o,x,i){
o[x] = -1 - i;
return o;
}, {});
Note that reduce
was introduced in ECMAScript 5.1, so it may not work in older browsers. If this is a concern, use the polyfill technique described in the linked documentation, or a simple for
-loop as Barmar's answer shows.
Upvotes: 0
Reputation:
var string = "A,B,C,D";
var res = {};
string.split(',').forEach(function(e, i) {
res[e] = - (i + 1);
});
console.log(res);//prints {A: -1, B: -2, C: -3, D: -4}
Upvotes: 0
Reputation: 782653
var letters = string.split(',');
var drp1 = {};
for (var i = 0; i < letters.length; i++) {
drp1[letters[i]] = -1 - i;
}
Upvotes: 2