Reputation: 23
How can I loop through my json data to find two specific key values e.g. weight = "8m" and meters = "7t" then return the name value of the object where these two values are found e.g. "25t".
data.json (Small sample)
[
{
"name": "20t",
"weight": ["1t","2t","3t","4t","5t"],
"meters": ["7m","8m","9m","10m","12m","14m","16m","18m"]
},
{
"name": "25t",
"weight": ["1t","2t","3t","4t","5t","6t","7t","8t"],
"meters": ["7m","8m","9m","10m","12m","14m","16m","18m","20m","22m"]
}
]
I'm able to loop through all the data using ngif and ngfor.
<div *ngIf="crane?.length">
<div *ngFor="let data of crane">
<p>{{data.name}}</p>
<p>{{data.weight}}</p>
<p>{{data.meters}}</p>
</div>
</div>
But I need to output only the specific name value where the weight and meters match the key value I want. Any idea on how I could achieve this? I'm quite new to angular, any help would be appreciated.
Upvotes: 2
Views: 6180
Reputation: 577
I hanged some of your sentence it did not make a lot of sense compared to the provided data but it looks like this:
const data = [
{
"name": "20t",
"weight": ["1t", "2t", "3t", "4t", "5t"],
"meters": ["7m", "8m", "9m", "10m", "12m", "14m", "16m", "18m"]
},
{
"name": "25t",
"weight": ["1t", "2t", "3t", "4t", "5t", "6t", "7t", "8t"],
"meters": ["7m", "8m", "9m", "10m", "12m", "14m", "16m", "18m", "20m", "22m"]
}
]
//ow can I loop through my json data to find two specific key values e.g. weight = "8t" and meters = "7m" then return the name value of the object where these two values are found e.g. "25t".
const result = data.filter(a => a.weight.find(w => w == "8t"))
.filter(a => a.meters.find(m => m == "7m"))
.map(a => a.name);
console.log(result)
Upvotes: 0
Reputation: 1053
Try this:
const data = [
{
"name": "20t",
"weight": ["1t","2t","3t","4t","5t"],
"meters": ["7m","8m","9m","10m","12m","14m","16m","18m"]
},
{
"name": "25t",
"weight": ["1t","2t","3t","4t","5t","6t","7t","8t"],
"meters": ["7m","8m","9m","10m","12m","14m","16m","18m","20m","22m"]
}
]
const w = "7t";
const m = "8m";
const filteredData = data
.filter(
(data) =>
data.weight
.some((weight) => weight === w)
&&
data.meters
.some((meter) => meter === m)
);
const keys = filteredData.map((data) => data.name);
console.log(keys);
Upvotes: 2