1

The idea is to insert data at a specific index provided by the user. I am familiar with the array insert methods but have no idea how to get the index of the data provided by the user to be able to insert data at that point. My plan was to first filter the data as per the inputs and then use that exact index to use the splice method. I did go as far as filtering the data but not beyond that. Any help would be appreciated. The JSON and the code are given below:

JSON

[
    {
        "district": "Kolkata",
        "ward_no": [
            {
                "ward": "6",
                "grievance": [
                    {
                        "serial_number": "0001",
                        "name" : "Mr.A"
                    },
                    {
                        "serial_number": "0002",
                        "name" : "Mr.B"
                    }
                ],
                "general": [
                    {
                        "serial_number": "0003",
                        "name" : "Mr.C"
                    },
                    {
                        "serial_number": "0004",
                        "name" : "Mr.D"
                    }
                ]
            },
            {
                "ward": "7",
                "grievance": [
                    {
                        "serial_number": "0005",
                        "name" : "Mr.E"
                    },
                    {
                        "serial_number": "0006",
                        "name" : "Mr.F"
                    }
                ],
                "general": [
                    {
                        "serial_number": "0007",
                        "name" : "Mr.G"
                    },
                    {
                        "serial_number": "0008",
                        "name" : "Mr.H"
                    }
                ]
            }
        ]
    },
    {
        "district": "Hooghly",
        "ward_no": [
            {
                "ward": "8",
                "grievance": [
                    {
                        "serial_number": "0009",
                        "name" : "Mr.I"
                    },
                    {
                        "serial_number": "0010",
                        "name" : "Mr.J"
                    }
                ],
                "general": [
                    {
                        "serial_number": "0011",
                        "name" : "Mr.K"
                    },
                    {
                        "serial_number": "0012",
                        "name" : "Mr.L"
                    }
                ]
            },
            {
                "ward": "9",
                "grievance": [
                    {
                        "serial_number": "0013",
                        "name" : "Mr.M"
                    },
                    {
                        "serial_number": "0014",
                        "name" : "Mr.N"
                    }
                ],
                "general": [
                    {
                        "serial_number": "0015",
                        "name" : "Mr.O"
                    },
                    {
                        "serial_number": "0018",
                        "name" : "Bruno Fernandes"
                    }
                ]
            }
        ]
    }
]

The code:

const queryNew = {
        district: "Kolkata",
        ward: "6",
        category: "grievance"
    };

    const data = {
        serial_number: "0034",
        name: "Donny Van De Beek"
    };

    const districtData = testData.filter(value => value.district === queryNew.district)[0];
    const indexArray = districtData.ward_no.filter((value, index) => value.ward === queryNew.ward)[0][queryNew.category];

    console.log(testData);

The query parameters are Kolkata, 6, and grievance with which I have filtered down to two levels. I just need to know how to go about inserting data at the above query.

P.S After applying the solutions, I get multiple occurrences of Donny Van De Beek.

enter image description here

import React from "react";
import testData from './testData.json';

const Display = () => {
    const queryNew = {
        district: "Kolkata",
        ward: "6",
        category: "grievance"
    };

    const data = {
        serial_number: "0034",
        name: "Donny Van De Beek"
    };

    const districtData = testData.find(value => value.district === queryNew.district);
    if (districtData) {
        const wardData = districtData.ward_no.find(value => value.ward === queryNew.ward);
        if (wardData) {
            wardData[queryNew.category].push(data);
        }
    }

    console.log(districtData);

    return(
        <div></div>
    );
}

export default Display;
coolhack7
  • 1,204
  • 16
  • 35
  • You want to update some particular object of Array. Right ? – Anuj Raghuvanshi Nov 27 '21 at 16:11
  • Using filter() is the wrong approach as it returns a new array. Use `find()` to return the object with the matching district and ward and then push the data into the grievance array of that object – charlietfl Nov 27 '21 at 16:11
  • Looking at your code it looks like the object is outside of the scope of the component. And because object is not deep copied you are adding stuff to the same array everytime your component is rendered. – Tushar Shahi Nov 27 '21 at 16:52
  • https://stackoverflow.com/questions/28876300/deep-copying-array-of-nested-objects-in-javascript . Look at this. `var testData2 = JSON.parse(JSON.stringify(testData));` Create a testData2 inside your component. This will be a deep copy – Tushar Shahi Nov 27 '21 at 16:54
  • @TusharShahi that seems to do the trick, although there's no way for me to know how or why the object is outside of the scope of the component. Will have to check though – coolhack7 Nov 27 '21 at 17:08
  • It is outside because it is coming from another file. Only thing insde the scope is the code inside `Display()`. That is why making a copy does the trick – Tushar Shahi Nov 27 '21 at 17:09

2 Answers2

1

I think filter() is not required for this. Filter is to remove some of the items from the array and get rest. Just use find() and keep getting the correct index from your nested arrays. find() will give you one of the matching indices from the array, based on a condition. If none of the array elements match, undefined is returned.

Since, objects are references. Any update you make will reflect in the main array.

let mainData = [
    {
        "district": "Kolkata",
        "ward_no": [
            {
                "ward": "6",
                "grievance": [
                    {
                        "serial_number": "0001",
                        "name" : "Mr.A"
                    },
                    {
                        "serial_number": "0002",
                        "name" : "Mr.B"
                    }
                ],
                "general": [
                    {
                        "serial_number": "0003",
                        "name" : "Mr.C"
                    },
                    {
                        "serial_number": "0004",
                        "name" : "Mr.D"
                    }
                ]
            },
            {
                "ward": "7",
                "grievance": [
                    {
                        "serial_number": "0005",
                        "name" : "Mr.E"
                    },
                    {
                        "serial_number": "0006",
                        "name" : "Mr.F"
                    }
                ],
                "general": [
                    {
                        "serial_number": "0007",
                        "name" : "Mr.G"
                    },
                    {
                        "serial_number": "0008",
                        "name" : "Mr.H"
                    }
                ]
            }
        ]
    },
    {
        "district": "Hooghly",
        "ward_no": [
            {
                "ward": "8",
                "grievance": [
                    {
                        "serial_number": "0009",
                        "name" : "Mr.I"
                    },
                    {
                        "serial_number": "0010",
                        "name" : "Mr.J"
                    }
                ],
                "general": [
                    {
                        "serial_number": "0011",
                        "name" : "Mr.K"
                    },
                    {
                        "serial_number": "0012",
                        "name" : "Mr.L"
                    }
                ]
            },
            {
                "ward": "9",
                "grievance": [
                    {
                        "serial_number": "0013",
                        "name" : "Mr.M"
                    },
                    {
                        "serial_number": "0014",
                        "name" : "Mr.N"
                    }
                ],
                "general": [
                    {
                        "serial_number": "0015",
                        "name" : "Mr.O"
                    },
                    {
                        "serial_number": "0018",
                        "name" : "Bruno Fernandes"
                    }
                ]
            }
        ]
    }
];

const queryNew = {
        district: "Kolkata",
        ward: "6",
        category: "grievance"
    };
const data = {
        serial_number: "0034",
        name: "Donny Van De Beek"
    };
    
let districtData = mainData.find(x => x.district === queryNew.district);
if(districtData){
    let ward = districtData.ward_no.find( x => x.ward === queryNew.ward);
    if(ward) 
      ward[queryNew.category].push(data);
}

console.log(districtData);

The if conditions are for checking. If you are confident your data exists, you can skip them.

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • Do you know why I get multiple occurrences of the inserted data? The length increases to 4 instead of being 3. Please check the latest screenshot – coolhack7 Nov 27 '21 at 16:40
  • @coolhack7 Is the code snippet output not what you expect? Are you doing something different? Please updated your new tried code – Tushar Shahi Nov 27 '21 at 16:43
  • I have updated the question with the code. It's right below the screenshot – coolhack7 Nov 27 '21 at 16:51
1

Try like this

const districtData = testData.find(
  (item) => item.district === queryNew.district
);
const wardData = districtData.ward_no.find(
  (item) => item.ward === queryNew.ward
);

wardData[queryNew.category].push(data);

console.log(testData);

Code => https://codesandbox.io/s/javascript-forked-qelt9?file=/index.js

Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43