简体   繁体   中英

How to Change value of nested array objects in javascript

I want to change the checked value base on the id kindly help me to solve this.I'll pass an id which have to match in each object in sub_cat and if any result found then change the check value

  "data": [
            {
                "id": "1",
                "name": "Electrical Repair & installation",
                "parent_id": "0",
                "image": "assets/images/Group66.png",
                "checked": "false",
                "sub_cat": [
                    {
                        "id": "7",
                        "name": "Sockets",
                        "parent_id": "1",
                        "image": "assets/images/Group66.png",
                        "checked": "false"
                    },
                    {
                        "id": "8",
                        "name": "Fans",
                        "parent_id": "1",
                        "image": "assets/images/Group67.png",
                        "checked": "true"
                    }
                ]
            },
         
           
        ]
  
yourObject.data[0].find(item => item.id === id_your_looking_for).checked = "true"

Ofc, you can wrap it in function and add a check if item is found, but i'm leaving it up to you:)

As you said, you will be checking on based some id. I have added one variable as chkID to check with sub_cat parent_id . you can check as per your requirement.

let chkID =1;
data.map(res => res.sub_cat.find((subItem) =>{ if(subItem.parent_id==chkID){
             subItem.checked = true;
             }}))

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