简体   繁体   中英

How i can filter and return a nested array of object?

someone can help me? i have a data structure like as:

contracts: [ 
0: {closedRequest: [{id: ... , name: ... } , {id: ... , name: ... }, {id: ... , name: ... }]},
1: {closedRequest: [{id: ... , name: ... } , {id: ... , name: ... }, {id: ... , name: ... }]},

]

Now i would filter this object for delete element in closedRequest that have a determined Id. I try to use with filter, but array not change.

How i can do it?

Example, i want exclude all element that have id (on closedRequest) = 3

so, if i have this structure:


contracts: [ 
0: {closedRequest: [{id: 2 , name: "a"} , {id: 3 , name: "b"}, {id: 4 , name: "c" }]},
1: {closedRequest: [{id: 2 , name: "a"} , {id: 3 , name: "b"}, {id: 4 , name: "c" }]},

]

i want have:

contracts: [ 
0: {closedRequest: [{id: 2 , name: "a"}  {id: 4 , name: "c" }]},
1: {closedRequest: [{id: 2 , name: "a"}  {id: 4 , name: "c" }]},

]

Example of my code:


client.contracts.forEach((c) =>
          c.closedRequests.filter((cr) => cr.requestID != requestID)
        );

i want have same object, but with filed of closedRequest edited.

Thanks

Assuming each item of contracts array consists of many fields, you can use array.map to transform the old array into a new one and array.filter in order to filter a nested array:

 let contracts = [ { closedRequest: [{id: 2 , name: "a"} , {id: 3 , name: "b"}, {id: 4 , name: "c" }] }, { closedRequest: [{id: 2 , name: "a"} , {id: 3 , name: "b"}, {id: 4 , name: "c" }] } ]; let filteredContracts = contracts.map(contract => ({ ...contract, closedRequest : contract.closedRequest.filter(x => x.id !== 3) })); console.log(filteredContracts);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM