0

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.

2
  • drp1 is an Object, not an Array Commented Aug 16, 2014 at 15:24
  • Take a look at String.split() at w3schools Commented Aug 16, 2014 at 15:24

4 Answers 4

2
var letters = string.split(',');
var drp1 = {};
for (var i = 0; i < letters.length; i++) {
    drp1[letters[i]] = -1 - i;
}
Sign up to request clarification or add additional context in comments.

Comments

0
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}

Comments

0

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.

Comments

0

You could use Array.map (see MDN)

var obj = {};
'A,B,C,D'.split(',').map(function (v, i) {this[a] = -(i+1);}, obj);

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.