简体   繁体   中英

Loop array of object to add new attribute didn't work

Question data format

[{ id: 0, name: "temp0", option: ["A", "B"] }, { id: 1, name: "temp1", option: ["A", "C"] }]

Code

 const mysqlQuery = () => {
        return new Promise((resolve) => {
            question.map(x => {
                mysqldb.query(sql, (err, rows, fields) => {
                    if (!err) {
                        x.totalQCount = rows[0].NumberOfQ //add new attribute and value
                        console.log(x.totalQCount) //display the value
                        console.log(x) //But not display new attribute and value
                        resolve(rows)
                    }
                })//end mysql query
            })//end for
        })
    } //end Promise
} //end for
 await mysqlQuery();

Thanks for your help.

As per my understanding of your question you wanted to add the property totalQCount to each object in your array without using map() or forEach() .

Set your totalQCount property using the below code:

   const questions = [
       {
            id:0,
            name: "temp0",
            option: ["A","B"]
        },
        {
            id:1,
            name: "temp1",
            option: ["A","C"]
        }
    ];

    for(let i=0;i<questions.length;i++){
      questions[i]['totalQCount '] = 0;
    }

    console.log(questions);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM