-2

I have a JSON response that looks like this:

[
    {
        "@level": "info",
        "@message": "Text"
    },
    {
        "@level": "error",
        "@message": "Text"
    },
    {
        "@level": "info",
        "@message": "Text"
    }
]

How can I filter the JSON response to only show Objects where "@level" === "error". I am aware how to generally filter JSON arrays in JS (e.g. as described here). However, this solution does not work if the key contains a special character like @.

What am I missing here?

maxiw46
  • 131
  • 1
  • 3
  • 11
  • 3
    [Use bracket notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors): `obj['@level']` not `obj.@level`. – Andy Aug 11 '22 at 11:02
  • Oh man... sometimes it's too easy. Thank you very much! – maxiw46 Aug 11 '22 at 11:05

1 Answers1

2

Works the same as in your linked answer, just use bracket notaion on the array:

let arr = [
    {
        "@level": "info",
        "@message": "Text"
    },
    {
        "@level": "error",
        "@message": "Text"
    },
    {
        "@level": "info",
        "@message": "Text"
    },
];

console.log(arr.filter(function(item){
    return item["@level"] == "error";
}));
enricog
  • 4,226
  • 5
  • 35
  • 54
  • 2
    Please don't answer questions where their duplicates [can be easily found](https://www.startpage.com/do/dsearch?query=javascript+key+special+characters&cat=web&pl=ext-ff&language=english&extVersion=1.3.0). Just close them as such. – Andy Aug 11 '22 at 11:06