在对象的 json 数组中找到一个键值并返回另一个带有角度的键值
Posted
技术标签:
【中文标题】在对象的 json 数组中找到一个键值并返回另一个带有角度的键值【英文标题】:Find a key value in json array of objects and return another key value with angular 【发布时间】:2019-06-07 22:46:15 【问题描述】:如何遍历我的 json 数据以找到两个特定的键值,例如weight =“8m”和meters =“7t”然后返回找到这两个值的对象的名称值,例如“25吨”。
data.json(小样本)
[
"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"]
]
我可以使用 ngif 和 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>
但我只需要输出重量和米与我想要的键值匹配的特定名称值。关于如何实现这一目标的任何想法?我对 Angular 很陌生,任何帮助将不胜感激。
【问题讨论】:
您可以添加示例输出吗? 【参考方案1】:试试这个:
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);
【讨论】:
【参考方案2】:我挂了你的一些句子,与提供的数据相比,它没有多大意义,但看起来像这样:
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)
【讨论】:
这行得通,但是,预先设置变量可以提供更大的灵活性,非常感谢以上是关于在对象的 json 数组中找到一个键值并返回另一个带有角度的键值的主要内容,如果未能解决你的问题,请参考以下文章
JavaScript:检查对象数组中是不是存在重复的键值并删除所有但最近添加的具有该键值的对象
jQuery .getJSON 返回到数组变量和 json 数组操作