使用 javascript 过滤 JSON 的嵌套数组(Airtable 结构)

Filtering Nested Array of JSON using javascript (Airtable structure)

我不是 javascript 程序员,但我需要编写一段 javascript 代码(在 HTML 页面中)以从 Airtable JSON 从 API 调用中获取的数组。我对此进行了大量研究并尝试了多种选择,但 none 对我有用。

我有一个基于 Airtable 的简单基础,包含以下数据:

    "records": [
         {
            "id": "reck1GtJ3KfhW9zEO",
            "fields": {
                "highlight": true,
                "price": 15,
                "product_name": "product 1",
                "prod_id": "G001"
            },
            "createdTime": "2021-09-21T20:01:42.000Z"
        },
        {
            "id": "rec7NJh86AK1S9kyN",
            "fields": {
                "highlight": true,
                "price": 50,
                "product_name": "product 2",
                "prod_id": "G002"
            },
            "createdTime": "2021-09-21T20:01:42.000Z"
        },
        {
            "id": "rec5JdK6pbuzsvXA1",
            "fields": {
                "price": 20,
                "product_name": "product 3",
                "prod_id": "G003"
            },
            "createdTime": "2021-09-21T20:01:42.000Z"
        },
        {
            "id": "recV39iR6tBzrmZ5s",
            "fields": {
                "price": 35,
                "product_name": "product 4",
                "prod_id": "G004"
            },
            "createdTime": "2021-09-21T20:01:42.000Z"
        }
    ]
}

我的代码如下:

(async() => {

URL= 'https://api.airtable.com/v0/*removed*';
let response = await fetch(URL, {headers:{ "Authorization":"Bearer *removed*"},});

result = await response.json();

// FILTERATION OPTION 1
//====================
const output_data = result.records.filter(d => d.product_name == "product 1");

console.log(result);
console.log(output_data);

})();

这个也试过了,没用


// FILTERATION OPTION 2
//====================
var output_data = result.records.filter(function (el) {
  return
  el.price == 35;
});

我想使用 prod_name 或价格,或 任何字段组合(包括 id) 来过滤上面的数据。非常感谢你的帮助。

试试这个:

result.records.filter(d => d.fields.product_name == "product 1");

应该是filter(d => d.fields.product_name == "product 1").

因为您的 product_name 键位于数组中每个节点的 fields 对象内。

const result = {"records":[{"id":"reck1GtJ3KfhW9zEO","fields":{"highlight":true,"price":15,"product_name":"product 1","prod_id":"G001"},"createdTime":"2021-09-21T20:01:42.000Z"},{"id":"rec7NJh86AK1S9kyN","fields":{"highlight":true,"price":50,"product_name":"product 2","prod_id":"G002"},"createdTime":"2021-09-21T20:01:42.000Z"},{"id":"rec5JdK6pbuzsvXA1","fields":{"price":20,"product_name":"product 3","prod_id":"G003"},"createdTime":"2021-09-21T20:01:42.000Z"},{"id":"recV39iR6tBzrmZ5s","fields":{"price":35,"product_name":"product 4","prod_id":"G004"},"createdTime":"2021-09-21T20:01:42.000Z"}]};
console.log(result.records.filter(d => d.fields.product_name == "product 1"));