I am trying to filter out a key, in this case, count
from a nested array of objects.
I have
let test = [
{
"id": "c3c6f410f58e5836431b473ebcf134756232d04f2bf35edff8",
"label": "Sector2",
"options": {
"62f92fab79ac81d933765bd0bbc4a1f5ea26cb3a088bcb4e6e": {
"index": 0,
"value": "Bob",
"label": "Bob",
"count": 1
},
"2fe91aa3567c0d04c521dcd2fc7e40d7622bb8c3f594d503da": {
"index": 1,
"value": "Student",
"label": "Student",
"count": 1
},
"c59ea1159f33b91a7f6edc6925be5e373fc543e4": {
"index": 2,
"value": "BBB",
"label": "BBB",
"count": 1
},
"c59ea1159f33b91a7f6edc6925be5e373fc54AAA": {
"index": 3,
"value": "Orange Duck",
"label": "Orange Duck",
"count": 1
}
}
},
{
"id": "f794c6a52e793ee6f5c42cd5df6b4435236e3495e951709485",
"label": "Brown Cow"
},
{
"id": "f794c6a52e793ee6f5c42cd5df6b4435236e3495e95170ZZZ",
"label": "Red Fish"
}
]
test = test.filter(item => item[0].options['count']);
but I am getting Cannot read properties of undefined
I am trying to filter out count from all elements of test that have options
desired output is
Thanks
[
{
"id": "c3c6f410f58e5836431b473ebcf134756232d04f2bf35edff8",
"label": "Sector2",
"options": {
"62f92fab79ac81d933765bd0bbc4a1f5ea26cb3a088bcb4e6e": {
"index": 0,
"value": "Bob",
"label": "Bob"
},
"2fe91aa3567c0d04c521dcd2fc7e40d7622bb8c3f594d503da": {
"index": 1,
"value": "Student",
"label": "Student"
},
"c59ea1159f33b91a7f6edc6925be5e373fc543e4": {
"index": 2,
"value": "BBB",
"label": "BBB",
"count": 1
},
"c59ea1159f33b91a7f6edc6925be5e373fc54AAA": {
"index": 3,
"value": "Orange Duck",
"label": "Orange Duck"
}
}
},
{
"id": "f794c6a52e793ee6f5c42cd5df6b4435236e3495e951709485",
"label": "Brown Cow"
},
{
"id": "f794c6a52e793ee6f5c42cd5df6b4435236e3495e95170ZZZ",
"label": "Red Fish"
}
]
4
Answers
filter()
is used to filter a portion of an array, not to delete nested keys of an object.The easiest way to achieve your desired result it to:
options
options
delete
to delete thecount
of the current objectYou could destructure the objects and remove unwanted property.
A generic solution to the OP’s problem does, regardless of the provided data-structure, structurally clone such an object while omitting any property which matches the provided set of to be omitted keys/property-names …