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.
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;