Home > Software design >  Dynamically generated object property undefined
Dynamically generated object property undefined

Time:03-14

I have this dynamically generated object whose properties displayed undefined. I don't seem to understand why it happened.

Pls help.

here is the code.

let submittionObject = {};
let submit = {};

let theSubmission = ['english', 'mathematics', 'r1Submitted', 'biology'];

    const theSubmit = theSubmission.map((item, index) => {
    if(item.indexOf('Submitted') !== -1){
        console.log(item.indexOf('Submitted'))
        submit = {...submittionObject, [item]: false};
    }else{
        submit = {...submittionObject,  [`r${index 1}Submitted`]: true};
    }
    return submit;
});



        const {r1Submitted, r2Submitted, r3Submitted, r4Submitted} = theSubmit;

The value of the destructured object should be a boolean of true or false but it instead displayed undefined

CodePudding user response:

Looks like you are looking for something like this :

const theSubmission = ['english', 'mathematics', 'r1Submitted', 'biology'];
const submittionObject = {};

theSubmission.forEach((subject, index) => {
  submittionObject[theSubmission[index]] = (subject.indexOf('Submitted') !== -1) ? true : false;
});

console.log(submittionObject);

CodePudding user response:

If you console.log(theSubmit), you can see that it is an array that contains the objects that contains the properties r1Submmitted, r2Submitted and so on.

[
  { r1Submitted: true },
  { r2Submitted: true },
  { r1Submitted: false },
  { r4Submitted: true }
]

This is because .map() returns an array

I'm not sure what you want exactly but is this what you are trying to achieve?

let theSubmission = ['english', 'mathematics', 'r1Submitted', 'biology'];
let submissionObject = {};
theSubmission.forEach((item, index) => {
    if (item.indexOf('Submitted') !== -1) {
        console.log(item.indexOf('Submitted'))
        submissionObject = { ...submissionObject, [item]: false };
    } else {
        submissionObject = { ...submissionObject, [`r${index   1}Submitted`]: true };
    }
})

console.log(submissionObject)

CodePudding user response:

map returns an array and property 'r1Submitted' and so on does not exist on an array. You will need to loop over the array to find the item with that property on it.

const r1Submitted = theSubmit.find(i => i.r1Submitted)

CodePudding user response:

Return a boolean in the callback. Try this,

let submittionObject = {};
let submit = {};

let theSubmission = ['english', 'mathematics', 'r1Submitted', 'biology'];

    const theSubmit = theSubmission.map((item, index) => {
    if(item.indexOf('Submitted') !== -1){
        console.log(item.indexOf('Submitted'))
        item = false;
    }else{
        item = true;
    }
    return item;
  });
  • Related