I have this kind of data that I pulled from my service and I'm importing it into an angular model. What I want to do here is to find those whose boolresult
value is true
in the model. I used the find method for this, but there is only 1 element, I want to get all of them, how can I achieve this?
Example Array
[
{
"ownername": "Owner",
"result": "Result1",
"clientname": "ClientName1",
"boolresult": true,
},
{
"ownername": "Owner",
"result": "Result2",
"clientname": "ClienName2",
"boolresult": true,
},
{
"ownername": "Owner",
"result": "Result3",
"clientname": "ClienName3",
"boolresult": false,
},
{
"ownername": "Owner",
"result": "Result4",
"clientname": "ClienName4",
"boolresult": false,
}
]
Here is the code I tried to convert this result to a model and show only the true ones.
private getAllResults(){
let apiEndpoint = "results"
this.httpRequestService.getApi(apiEndpoint, false).subscribe(resultRequest => {
this.serviceResults = resultRequest; // This is Array to MyModel
this.serviceResults.sort((a, b) => new Date(b.createddate).getTime() - new Date(a.createddate).getTime());
console.log(this.serviceResults)
this.approvedResults = this.serviceResults.find(item => item.boolresult == true) // I Tried this
console.log(this.approvedResults)
})
}
When I try this way, only 1 element is showing, I want to show all the values with boolresult
true
.How can I provide this?
CodePudding user response:
user filter method rather than find method
find()=> The first element in the array that satisfies the provided testing function
filter()=>A shallow copy of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function
var serviceResults=[
{
"ownername": "Owner",
"result": "Result1",
"clientname": "ClientName1",
"boolresult": true,
},
{
"ownername": "Owner",
"result": "Result2",
"clientname": "ClienName2",
"boolresult": true,
},
{
"ownername": "Owner",
"result": "Result3",
"clientname": "ClienName3",
"boolresult": false,
},
{
"ownername": "Owner",
"result": "Result4",
"clientname": "ClienName4",
"boolresult": false,
}
]
var approvedResults = serviceResults.filter(item => item.boolresult == true) // I Tried this
console.log(approvedResults)
CodePudding user response:
let sampleArray = [
{
ownername: "Owner",
result: "Result1",
clientname: "ClientName1",
boolresult: true
},
{
ownername: "Owner",
result: "Result2",
clientname: "ClienName2",
boolresult: true
},
{
ownername: "Owner",
result: "Result3",
clientname: "ClienName3",
boolresult: false
},
{
ownername: "Owner",
result: "Result4",
clientname: "ClienName4",
boolresult: false
}
];
// Get all the results whose boolresult is 'true'
// Solution - 1
sampleArray = sampleArray.filter((element) => element.boolresult);
console.log("Result ==>>", sampleArray);
// Solution - 2
let result = [];
sampleArray.forEach(element => {
if (element.boolresult) {
result.push(element)
}
})