0

I really want to take variables from array index to its own array index property. now here's my code so far, but it didn't work. Hopefully this would visuallize you to what I mean.

const CHARACTERS: Character[] = [
  { id: 1, name: 'hei', image: './c' + this.id + '/' + 'portrait.png'},
  { id: 2, name: 'ok', image: './c' + this.id + '/' + 'portrait.png'},
  { id: 3, name: 'whatever', image: './c' + this.id + '/' + 'portrait.png'}
]

I want the image property resulting value to

./c1/portrait.png
./c2/portrait.png
./c3/portrait.png

Something like that.

2 Answers 2

1

You can create a function e.g

const createCharacter = ({id, name}) => ({ id, name, image: './c' + id + '/' + 'portrait.png'})

const CHARACTERS: Character[] = [
  createCharacter({id: 1, name: 'hei'}),
  createCharacter({id: 2, name: 'ok'}),
  ... 
]
Sign up to request clarification or add additional context in comments.

Comments

1
const NAMES: {id: number, name: string}[] = [
  { id: 1, name: 'hei'}
  { id: 2, name: 'ok'}
  { id: 3, name: 'whatever'}
]

const CHARACTERS: Character[] = NAMES.map(item, ({id,name}) => {
  return {id, name, image: './c' + id + '/' + 'portrait.png'
});

2 Comments

what version of angular did you using? I got errors
I fixed the problem

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.