Alisa F. Kennedy
Alisa F. Kennedy

Reputation: 171

javascript increment from number to string

How can I parse number to string for increment? Do I have to make 2 line statement? Below code is not valid.

['a', 'b'].map((o,i)=>({myStr: ++i.toString()}))

ignore the array, it's just sample, I expect this [{myStr: "1"},{myStr:"2"}] where i is the index of map.

Upvotes: 1

Views: 149

Answers (3)

Leonid Pyrlia
Leonid Pyrlia

Reputation: 1702

Wrap ++i in a String constructor:

['a', 'b'].map((o,i)=>({myStr: String(++i)}))

Upvotes: 1

vadim savin
vadim savin

Reputation: 259

 var arr = ['a', 'b'];
 var newArr = arr.map((o,i)=>({myStr: (++i).toString()}))

Upvotes: 0

Marcos Casagrande
Marcos Casagrande

Reputation: 40374

You have to wrap ++i: (++i).toString();

const res = ['a', 'b'].map((o,i) => ({myStr: (++i).toString()} ));
console.log(res);

You can also use template literals:

 const res = ['a', 'b'].map((o,i) => ({myStr: `${++i}`} ));
 console.log(res);

Upvotes: 2

Related Questions