I would like to find a solution that returns the following result when any of the property "value" is true.
This is what I have tried so far, but so far it has not worked
public displayCondition(data:any){
const items = data.status.map((status: { value: boolean; }) =>{
staus.value === true;
})
return items;
}
Input
const data: [
{
name: "php",
status: [
{
value: "true"
},
{
value: "false"
}
]
},
{
name: "java",
status: [
{
value: "false"
},
{
value: "false"
}
]
}
]
Output
[
{
name: "php",
status: [
{
value: "true"
},
{
value: "false"
}
]
}
]
CodePudding user response:
Your data structure has an antipattern: using strings "true"
and "false"
as booleans true
and false
. I suggest converting it to real booleans unless you have a very compelling reason to do otherwise. It should be possible to say if (data[0].status[0]) {...}
but that's an always-true condition when you use strings.
In your original code, the condition staus.value === true;
is always false as it compares a string with a boolean.
Here's how to make the conversion:
const data = [
{
name: "php",
status: [
{value: "true"},
{value: "false"}
]
},
{
name: "java",
status: [
{value: "false"},
{value: "false"}
]
}
];
data.forEach(e => e.status.forEach(e => {
e.value = e.value === "true";
}));
console.log(data);
Back to the main problem. map
isn't used to search an array; it's used to apply a transformation on each entry in an array.
Try .filter
(return all elements matching a predicate) and .some
(return true if the predicate is true for any item in an array, otherwise false):
const data = [
{
name: "php",
status: [
{value: "true"},
{value: "false"}
]
},
{
name: "java",
status: [
{value: "false"},
{value: "false"}
]
}
];
const result = data.filter(e => e.status.some(e => e.value === "true"));
console.log(result);
// or if you made the boolean conversion:
//const result = data.filter(e => e.status.some(e => e.value));
Use .find
rather than .filter
if you want only the first item that matches the predicate (or null if none matched).
CodePudding user response:
You can use the Array#filter
and Array#some
methods and object destructuring as follows:
const data = [ { name: "php", status: [ { value: "true" }, { value: "false" } ] }, { name: "java", status: [ { value: "false" }, { value: "false" } ] } ],
output = data.filter(
({status}) => status.some(
({value}) => value === "true"
)
);
console.log( output );