How do we filter an object in angular or typescript to remove object that has an empty value for example remove object where annualRent === null
. Also what rounding solution can we use to round for example 2.8333333333333335 to 2.83 and remove the other additional decimals like 3333 ....
Thanks.
what I tried and have in mind , something like
array.filter((x): x is MyType => x !== null);
#sample object
[
{
"id": 0,
"type": 0,
"startDate": "2021-09-27T16:00:00.000Z",
"endDate": "2021-09-29T16:00:00.000Z",
"endDateString": "09/30/2021",
"annualRent": "23232",
"endDateError": null
},
{
"id": 1,
"startDate": "2021-09-27T16:00:00.000Z",
"endDate": "2021-09-29T16:00:00.000Z",
"endDateString": null,
"annualRent": null,
"prevEndDate": "2021-09-29T16:00:00.000Z",
"useFMV": false
}
]
CodePudding user response:
You can use the filter method as follows:
arr = [
{
"id": 0,
"type": 0,
"startDate": "2021-09-27T16:00:00.000Z",
"endDate": "2021-09-29T16:00:00.000Z",
"endDateString": "09/30/2021",
"annualRent": "23232",
"endDateError": null
},
{
"id": 1,
"startDate": "2021-09-27T16:00:00.000Z",
"endDate": "2021-09-29T16:00:00.000Z",
"endDateString": null,
"annualRent": null,
"prevEndDate": "2021-09-29T16:00:00.000Z",
"useFMV": false
}
].filter(obj=> obj.annualRent !== null);
console.log(arr);
You can use the method toFixed()
to get the number of digits as follows
let num = 2.8333333333333335;
let roundedNum = num.toFixed(2)
console.log(roundedNum);
CodePudding user response:
Try this to filter out objects and at the same time apply rounding to an object property value and debug the results to the console:
let objectList: any[] =
[
{
"id": 0,
"type": 0,
"startDate": "2021-09-27T16:00:00.000Z",
"endDate": "2021-09-29T16:00:00.000Z",
"endDateString": "09/30/2021",
"annualRent": "23232",
"monthlyPay": "2833.3333333333335",
"endDateError": null
},
{
"id": 1,
"startDate": "2021-09-27T16:00:00.000Z",
"endDate": "2021-09-29T16:00:00.000Z",
"endDateString": null,
"annualRent": null,
"monthlyPay": null,
"prevEndDate": "2021-09-29T16:00:00.000Z",
"useFMV": false
},
{
"id": 2,
"startDate": "2021-09-27T16:00:00.000Z",
"endDate": "2021-09-29T16:00:00.000Z",
"endDateString": null,
"annualRent": "12222",
"monthlyPay": "5000.8889",
"prevEndDate": "2021-09-29T16:00:00.000Z",
"useFMV": false
}
];
console.log('number of items in list 1 = ' objectList.length);
objectList = objectList.filter(x => x['annualRent'] !== null)
.map((element: any) =>
{
console.log('monthly pay before = ' element['monthlyPay']);
let num: number = parseFloat(element['monthlyPay']);
element['monthlyPay'] = num.toFixed(2);
console.log('monthly pay after = ' element['monthlyPay']);
return element;
});
console.log('number of items in original list = ' objectList.length);