在对象的json数组中找到一个键值,然后返回另一个带有angular的键值

时间:2019-01-13 21:01:23

标签: javascript arrays json angular

如何遍历json数据以找到两个特定的键值,例如重量=“ 8m”,米=“ 7t”,然后返回找到这两个值的对象的名称值,例如“ 25t”。

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>

但是我只需要输出重量和仪表与我想要的键值匹配的特定名称值。关于如何实现此目标的任何想法吗?我对棱角还很陌生,任何帮助将不胜感激。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

我挂了一些句子,与提供的数据相比,这没有什么意义,但是看起来像这样:

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)