我真的想从数组索引中获取变量到它自己的数组索引属性。现在这里是我的代码到目前为止,但它没有用。希望这会使你明白我的意思。
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'}
]
我希望image
属性结果值为
./c1/portrait.png
./c2/portrait.png
./c3/portrait.png
类似的东西。
答案 0 :(得分: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'
});
答案 1 :(得分:1)
您可以创建一个功能,例如
const createCharacter = ({id, name}) => ({ id, name, image: './c' + id + '/' + 'portrait.png'})
const CHARACTERS: Character[] = [
createCharacter({id: 1, name: 'hei'}),
createCharacter({id: 2, name: 'ok'}),
...
]