How do I delete the array which contains a matching key value in a multi-dimensional array?
I am using only javascript with no frameworks.
I am parsing the following array with the following:
"services": [
{
"_id": "62473476313228338b3320cc",
"name": "test",
"fields": [
{
"name": "this",
"type": "mulDropdown",
"_id": "624f19bbec96c92076e98095",
"data": [
{
"_id": "6250aaa4e5d0f222d74311d3",
"name": "this too",
"hidden": "0"
},
{
"_id": "62546392fa98b17106d35d7c",
"name": "this three",
"hidden": "0"
},
{
"_id": "6254639efa98b17106d35d7d",
"name": "this4",
"hidden": "1"
}
],
"hidden": "0"
},
{
"isRequire": false,
"name": "another this",
"type": "dropdown",
"_id": "624f3bb4fda95e5fdf978016",
"data": [
{
"_id": "625463d5fa98b17106d35d80",
"name": "another",
"hidden": "1"
},
{
"_id": "625463e6fa98b17106d35d81",
"name": "another2",
}
],
"hidden": "0"
}
]
}
]
services.forEach((item, index) => {
item.fields.forEach((i, ind) => {
if (i.type == "mulDropdown") {
i.data.forEach(function (item, index) {
if (item.hidden == '1') {
delete item["name"];
At this point I can see the values and can remove the keys with 'delete item' but I need to delete the entire data array with something like 'delete data[2]'
I've tried various filter, splice, remove examples but I can't manage to make it work on my array.
Desired array:
"services": [
{
"_id": "62473476313228338b3320cc",
"name": "test",
"fields": [
{
"name": "this",
"type": "mulDropdown",
"_id": "624f19bbec96c92076e98095",
"data": [
{
"_id": "6250aaa4e5d0f222d74311d3",
"name": "this too",
"hidden": "0"
},
{
"_id": "62546392fa98b17106d35d7c",
"name": "this three",
"hidden": "0"
}
],
"hidden": "0"
},
{
"isRequire": false,
"name": "another this",
"type": "dropdown",
"_id": "624f3bb4fda95e5fdf978016",
"data": [
{
"_id": "625463d5fa98b17106d35d80",
"name": "another",
"hidden": "1"
},
{
"_id": "625463e6fa98b17106d35d81",
"name": "another2",
}
],
"hidden": "0"
}
]
}
]
CodePudding user response:
You could map thru the keys and filter the data property based on "type" = "mulDropdown"
and "hidden" !== "1"
. Please note this will modify the original object. But from your example, seemed like you may be ok with that.
let obj = {
services: [
{
_id: '62473476313228338b3320cc',
name: 'test',
fields: [
{
name: 'this',
type: 'mulDropdown',
_id: '624f19bbec96c92076e98095',
data: [
{
_id: '6250aaa4e5d0f222d74311d3',
name: 'this too',
hidden: '0'
},
{
_id: '62546392fa98b17106d35d7c',
name: 'this three',
hidden: '0'
},
{
_id: '6254639efa98b17106d35d7d',
name: 'this4',
hidden: '1'
}
],
hidden: '0'
},
{
isRequire: false,
name: 'another this',
type: 'dropdown',
_id: '624f3bb4fda95e5fdf978016',
data: [
{
_id: '625463d5fa98b17106d35d80',
name: 'another',
hidden: '1'
},
{
_id: '625463e6fa98b17106d35d81',
name: 'another2'
}
],
hidden: '0'
}
]
}
]
}
obj.services.map((s) => {
s.fields.map((f) => {
f.data = f.type === 'mulDropdown' ? f.data.filter((d) => d.hidden !== '1') : f.data
})
})
console.log(obj)