1

How can I append a string to each element from a string array in typescript I have an array like const original = ['a', 'b', 'c'] I want to make it as const original_string = ['i am key a', 'i am key b', 'i am key c'] how can I do that? maybe something like const original_string = original.map(() => ${'i am key'})? I have following but it does not work

const original_string = original.forEach((item)=> (`i am key ${item}`));

3 Answers 3

5

const original = ['a', 'b', 'c'];
const original_string = original.map(item => `i am key ${item}`)
console.log({original, original_string});

You want to use map which will put the value in the array for you.

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

Comments

2
const original = ['a', 'b', 'c'];
const original_string : any = [];

original.map((a) => {
  original_string.push("Key " + a);
});

console.log(original_string);

Comments

0

You can use map function to create a new array out of existing array, in this case you want to create original_string out of original array.

For eg. You can do this.

const original = ['a', 'b', 'c'];
const original_string: string[] = original.map((key: string) => {
   return `I'm key ${key}`;
});

console.log(original_string);

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.