Home > Mobile >  filter array to limited key in reactjs
filter array to limited key in reactjs

Time:11-15

I have reactjs app and i have the following result returned from mongodb. I am looking to filter the result to only contain _id and customername array key. Example:{"Records":[{"_id":"6190d42febf87a4b4da5fcb0","customername":"Henry"} , {"_id":"6190b608b17338658902ae0b", "customername":"Henry"}} Any help would be appreciated.

{"Records":[{"_id":"6190d42febf87a4b4da5fcb0","customername":"Henry","grade":"D","entrydate":"14/11/2021, 05:17:30 pm","reject":"10","clone":"D24","remark":"","selectedprocess":"raw-material","selectedcategory":"nitrogen","weight":[10,30],"totalweight":40},{"_id":"6190b608b17338658902ae0b","customername":"Henry","grade":"A","entrydate":"14/11/2021, 03:08:53 pm","reject":"5","clone":"D24","remark":"Mr GunGUn","selectedprocess":"raw-material","selectedcategory":"nitrogen","weight":[5,30],"totalweight":35}]}

CodePudding user response:

You can use the Array.map to achieve the required result.

var updatedRecords = records.map((record)=> ({"_id": record._id,customername: record.customername })) 

The updatedRecords would consists of a new array that would only contain the id and the customername.

The preferred way would be that the backend handles this

CodePudding user response:

Shortest way I can think of:

const updatedRecords = records.map(({_id, customername})=> ({_id, customername}));
  • Related