brianfr82 brianfr82 - 4 months ago 20
JSON Question

JavaScript Cannot set property of undefined

I'm a novice backend developer and I've been tasked with adding some react features and I'm totally out of my depth. The following code generates the exception "Cannot set property '1' of undefined". The first element is id:1 and name:"". I don't think the empty string has anything to do with my problem though since I've tried hardcoding a string and I get the same exception.

payment_code: {
label: 'Payment Code',
value: 'payment_code',
choices: adminSalesStore.paymentCodes.map((payment_code) => {
console.log(payment_code);
console.log(payment_code['id']);
console.log(payment_code['name']);
displayChoices.payment_code[payment_code['id']] = payment_code['name'];
return {
label: payment_code['id'],
value: payment_code['name']
}
}),
type: 'choice'
},


I really don't understand the error because payment_code['id'] and payment_code['name'] are not null or undefined. The log statements confirm this. Sorry about the super basic question but I've googled the issue pretty extensively and this error still makes absolutely no sense. There's similar functions in the same class and they all work. However, the other methods use const arrays and I need to pull my values from the db.

Answer

I'm guessing that the property you show is part of the assignment to displayChoices, i.e. it's something like:

displayChoices = {
    ...
    payment_code: {
        label: "Payment Code",
        value: 'payment_code',
        choices: adminSalesStore.paymentCodes.map((payment_code) => {
            console.log(payment_code);
            console.log(payment_code['id']);
            console.log(payment_code['name']);
            displayChoices.payment_code[payment_code['id']] = payment_code['name'];
            return {
                label: payment_code['id'],
                value: payment_code['name']
            }
        }),
        type: 'choice'
    },
    ...
};

The problem is that until this statement finishes, there's no displayChoices.payment_code property, so you can't assign to displayChoices.payment_code[anything].

You should do that assignment after you finish the first assignment.

displayChoices = {
    ...
    payment_code: {
        label: "Payment Code",
        value: 'payment_code',
        type: 'choice'
    },
    ...
};

displayChoices.choices = adminSalesStore.paymentCodes.map((payment_code) => {
    console.log(payment_code);
    console.log(payment_code['id']);
    console.log(payment_code['name']);
    displayChoices.payment_code[payment_code['id']] = payment_code['name'];
    return {
        label: payment_code['id'],
        value: payment_code['name']
    }
}),