简体   繁体   中英

How to change first array JSON data in Javascript?

Hi I am changing json data using onChange event. The first element of array data is not getting changed & other json data are getting changed. How can we change the first data also ? below is my code -

const onChange = (
        selectType: string,
        selectedValue: string,
        selectedId: number
    ): void => {
        
        const arrayData = arrayData1 // where arrayData1 is state
        
        // get question data to to make the changes
        const myQues = arrayData.find(
            (ques) => ques.quesId=== selectedId
        );

        if (myQues) {
            switch (selectType) {
                case Enum.DEMO_VALUE:

                    myQues.answerList.map((answer) => {

                        if(typeof selectedValue === 'string' && 
                        parseInt(selectedValue) <= answer.high  && parseInt(selectedValue) >= answer.low) {
                            answer.value1 = selectedValue;
                            answer.value2 = selectedValue;
                            answer.answered = true
                        } else {
                            answer.value1 = null;
                            answer.value2 = null;
                            answer.answered = false
                        }
                    });
                
                    break;
            }
        }
        setMyArrayData([...arrayData]);
        
    };

where

answerList = [{
    value1 : null,
    value2 : null,
    answered : false,
    low : 0,
    high : 9
},
{
    value1 : 12,
    value2 : 12,
    answered : true,
    low : 10,
    high : 19
}
{
    value1 : null,
    value2 : null,
    answered : false,
    low : 20,
    high : 300
}]

default answer is 12 . When I change value from 12 to 1 then it should go to answerList[0] and rest two should be null and answered should be false and it is working fine also. But when I change value from 1 to 15 again then it should go to answerList[1] and answerList[0] & answerList[2] should be null and answered false but it's not working properly. Both answerList[0] & answerList[1] are same. Again when I change value from 15 to 151 then answerList[0] & answerList[2] are same while answerList[1] gets fine. In short answerList[0] is not getting changed in any condition while answerList[1] & answerList[2] are getting changed. Why is that ? How can we resolve it ?

answerlist[0]["value"] = 1; 

try this sir basically, you want to access the first element in your json array, then in that object you want to change the value property.

more on this here: How can I access and process nested objects, arrays or JSON?

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