Home > Software design >  Filter json element with values stored into another object
Filter json element with values stored into another object

Time:12-31

I have the following JSON:

var json = [
    {
        "Key1": some text...,
        "Key2": some text...,
        "Key3": [
            {
                "Key": "Key 1",
                "Value": "1",
            },
            {
                "Key": "Key 2",
                "Value": "1",
            }
        ]
    },
    {
        "Key1": some text...,
        "Key2": some text...,
        "Key3": [
            {
                "Key": "Key 1",
                "Value": "2",
            },
            {
                "Key": "Key 2",
                "Value": "2",
            }
        ]
    },
    {
        "Key1": some text...,
        "Key2": some text...,
        "Key3": [
            {
                "Key": "Key 1",
                "Value": "3",
            },
            {
                "Key": "Key 2",
                "Value": "3",
            }
        ]
    },
]

Then I have the following var

var items = [1, 3];

What I need to do is to filter json to only show the items which Key 2 value exists into items object. I'm trying doing the following:

var res = json.filter(item => items.includes(item.Key3.find(x => x.Key === "Key 2").Value));

The above code is returning an empty result ([]). There is another way to handle this? And what I'm doing wrong?

var json = [
   {
      "Key1":"some text...",
      "Key2":"some text...",
      "Key3":[
         {
            "Key":"Key 1",
            "Value":"1"
         },
         {
            "Key":"Key 2",
            "Value":"1"
         }
      ]
   },
   {
      "Key1":"some text...",
      "Key2":"some text...",
      "Key3":[
         {
            "Key":"Key 1",
            "Value":"2"
         },
         {
            "Key":"Key 2",
            "Value":"2"
         }
      ]
   },
   {
      "Key1":"some text...",
      "Key2":"some text...",
      "Key3":[
         {
            "Key":"Key 1",
            "Value":"3"
         },
         {
            "Key":"Key 2",
            "Value":"3"
         }
      ]
   }
];

var items = [1, 3];
var res = json.filter(item => items.includes(item.Key3.find(x => x.Key === "Key 2").Value));
console.log(res);

CodePudding user response:

includes() performs a strict equality check. So it doesn't match if items contains numbers but item.Key3 contains strings.

You should parse the string in the Value to an integer.

var res = json.filter(item => items.includes(parseInt(item.Key3.find(x => x.Key === "Key 2").Value)));
  • Related