SkyeBoniwell
SkyeBoniwell

Reputation: 7092

getting specific data from an object

I'm trying to figure out how to get the data I need out of an object I created.

I previously had my app data stored in 2 arrays like this:

const AVATARS = {
    avatar1: require('./images/avatar_1.jpg'),
    avatar2: require('./images/avatar_2.jpg')
}

export const STATS = {
    stats1: "\nHP: 124\n" +
            "INT: 23\n" +
            "CHR: 13\n",

    stats2: "\nHP: 423\n" +
            "INT: 24\n" +
            "CHR: 11\n"
}

To populate the app page, I would use these two functions to get the data:

import { AVATARS } from './arrays'
import { STATS } from './arrays'

//returns data based on array position(num)
export function getAvatar(num) {
    return AVATARS['avatar' + num];
}

export function getStats(num) {
    return STATS['stats' + num];
}

I recently decided to switch to an object where I store all the data, like this:

export var Characters = [
    {
        id: 1,
        Name: "Abe",
        HitPointValue: "124",
        StrengthValue: "12",
        IntelligenceValue: "14",
        WisdomValue: "16",
        DexterityValue: "12",
        ConstitutionValue: "10",
        CharismaValue: "17",
        Avatar: require('./images/avatar_7.jpg')
    },
    {
        id: 2,
        Name: "Jake",
        HitPointValue: "141",
        StrengthValue: "21",
        IntelligenceValue: "6",
        WisdomValue: "5",
        DexterityValue: "8",
        ConstitutionValue: "20",
        CharismaValue: "10",
        Avatar: require('./images/avatar_2.jpg')
    }
]

But now that I did that, I have no idea how to get the needed data. Obviously my old functions won't work. Is there a way to pick which data I need for a given page?

For example, if I only need the Name and Avatar for one page, but I might need the stats for another page.

Thanks!

Upvotes: 0

Views: 26

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281686

You can modify you functions to accept id like

import {characters} from './arrays';

//returns data based on array position(id)
export function getAvatar(id) {
    var idx = characters.findIndex((val) => val.id == id);

    return characters[idx].Avatar;
}

export function getName(id) {
     var idx = characters.findIndex((val) => val.id == id);
    return characters[idx].Name;
}

Upvotes: 1

Related Questions