1

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.

4
  • 1
    What is the input and expected output? Commented Jul 7, 2018 at 14:44
  • The input array doesn't contain numbers? What exactly would your expected output be? And why? Commented Jul 7, 2018 at 14:45
  • @LukStorms updated my answer Commented Jul 7, 2018 at 14:47
  • 2
    ['a', 'b'].map((o,i)=>({myStr: String(++i)})) Commented Jul 7, 2018 at 14:49

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

Wrap ++i in a String constructor:

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

Comments

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

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.