SkyeBoniwell
SkyeBoniwell

Reputation: 7122

Error undefined is not a function

I have arrays I'm passing via props like this:

{
    id: 1,
    Name: "Abe",
    HitPointValue: "124",
    StrengthValue: "12",
    IntelligenceValue: "14",
    WisdomValue: "16",
    DexterityValue: "12",
    ConstitutionValue: "10",
    CharismaValue: "17",
    Avatar: require('./images/avatar_1.jpg')
}

I receive these in a component like this:

static navigationOptions = ({ navigation }) => {
    const {char} = state.params;
}

When I write out the properties of the array one by one like this, it works:

    render() {
        const { params } = this.props.navigation.state;
        return (
            <View>
                <Text>
                    Name: {params.char.Name}{"\n"}
                </Text>
            </View>
        )   
}

But when I try to use "map" to loop through the array(like below), I just get an error that states "

undefined is not a function (params.char.map)

.

render() {
    const { params } = this.props.navigation.state;
    return (
        <View>
            {params.char.map(c =>
                <Text>
                    {c.key} : {c.value} {"\n"}
                </Text>
            )}
        </View>
    )
 }

I'm trying to follow this guide, Lists and Keys but it's not working.

What could I be doing wrong?

thanks!

Upvotes: 1

Views: 76

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104499

Because that data is not an array, and map only works with array. Use Object.entries first then use map.

Write it like this:

render() {
    const { params } = this.props.navigation.state;
    return (
        <View>
            {Object.entries(params.char).map(([key,value], index) =>
                <Text key={key}>
                    {key} : {value} {"\n"}
                </Text>
            )}
        </View>
    )
 }

Check this snippet:

let obj = {
    id: 1,
    Name: "Abe",
    HitPointValue: "124",
    StrengthValue: "12",
    IntelligenceValue: "14",
    WisdomValue: "16",
    DexterityValue: "12",
    ConstitutionValue: "10",
    CharismaValue: "17",
};

Object.entries(obj).map(([key, value], index) => console.log(key, value, index))

Upvotes: 3

Related Questions