Reputation: 171
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
Reputation: 1702
Wrap ++i
in a String
constructor:
['a', 'b'].map((o,i)=>({myStr: String(++i)}))
Upvotes: 1
Reputation: 259
var arr = ['a', 'b'];
var newArr = arr.map((o,i)=>({myStr: (++i).toString()}))
Upvotes: 0
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