0

I've an json data that has an array. Each element of an array has array named items. I want to remove the inner array element if the string doesnot match the itemName. I tried using filter method but its not working as expected. It only returns the matching inner array elements but all the outer array elements are removed too. P.S see the code, json data, the output I get and the expected output. Thanks in advance

Code:

const update2 =
 state.menuResponse.map(
       item => {
        return item.items.filter(item => (item.itemName).includes("C"))
})

console.log("menuSearcheddd", update2)

Json data

{
  "data": [
    {
      "menuHeader": "Starters",
      "items": [
        {
          "itemId": "1",
          "itemName": "burger",
        },
        {
          "itemId": "ITD1ZYTH",
          "itemName": "Cheese balls",
        }
      ]
    },
    {
      "menuHeader": "string",
      "items": [
        {
          "itemId": "1",
          "itemName": "burger",
        },
        {
          "itemId": "2",
          "itemName": "burger-non veg",
        }
      ]
    }
  ]
}

Output:

{
  "data": [
    {
      "items": [
        {
          "itemId": "ITD1ZYTH",
          "itemName": "Cheese balls",
        }
      ]
    },
    {
      "items": []
    }
  ]
}

What should be?

{
  "data": [
    {
      "menuHeader": "Starters",
      "items": [
        {
          "itemId": "ITD1ZYTH",
          "itemName": "Cheese balls",
        }
      ]
    },
    {
      "menuHeader": "string",
      "items": []
    }
  ]
}

2 Answers 2

2

The outer elements are removed not because of the filter method, but because of the map method. See, in your map method you are disregarding every other property because you only return what you process on the items array.

So, code should look more like this:

const update2 = state.menuResponse.map(item => ({ ...item, items: item.items.filter(subItem => subItem.itemName.includes('C')) }));

So that from your map method you are returning everything that was inside you object before processing it and only modifying the items property by filtering the array like you have already done it.

Haven't managed to test it, but should work, in theory...

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect answer for nested array inside array delete.
1
var list = this.state.materialList.filter(item => {
            //Filter Inner Array 
            var innerData = item.data.filter(dataItem => {
                return dataItem.qty > 0
            })
            // Assign value
            item.data = innerData;
            return item.Id > 0
        })
 console.log('Filtered List ',list);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.