Search code examples
typescriptangular7ecmascript-5ngrx-store

How to filter parent object by it's children id?


I am getting backend response like this:

{
  "ReturnModel": {
    "Id": 20,
    "Name": "tserror.JPG,typeIssue.JPG",
    "Description": "testing",
    "SubjectId": 100001,
    "SubjectTypeId": 100001,
    "SubjectLevelId": 100001,
    "SubjectOptionId": 100001,
    "LanguageId": 100001,
    "BlobFileUpload": [
      {
        "FileId": 27,
        "FileName": "tserror_20190410110826.JPG",
        "FileDescription": "Upload",
        "CourseId": 20,
        "CourseFileUpload": null
      },
      {
        "FileId": 28,
        "FileName": "typeIssue_20190410110826.JPG",
        "FileDescription": "Upload",
        "CourseId": 20,
        "CourseFileUpload": null
      }
    ]
  }
}

From the above json value, I need to filter the parent from it's BlobFileUpload - FileId. For that, I tried the following, but not works. any suggest me the correct approach?

case fileActions.RemoveFileSuccess.TYPE :

            const fileId = (<fileActions.RemoveFileSuccess>action).payload.Id;

            return {
                ...state,
                uploadedFiles : state.uploadedFiles.filter(file => file.BlobFileUpload.filter(blob => blob.FileId !== fileId))
            }

Solution

  • I think what you need is state.uploadedFiles.filter(file => file.BlobFileUpload.some(blob => blob.FileId !== fileId))

    Array.protptype.some() checks if any item in the array is truthful for the provided predicate and returns a boolean.

    Array.prototype.filter() expects a predicate which returns a boolean, but filter itself returns an array and an array is always truthy. That's why it was not filtering for you.