I'm not a javascript programmer, but I have a need to write a piece of javascript code (in an HTML page) to filter data from an Airtable JSON array fetched from an API call. I've researched this a lot and tried several options, but none of them worked for me.
I have a simple base on Airtable with the following data:
"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"
}
]
}
The code I have is as follows:
(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);
})();
Also tried this, didn't work
// FILTERATION OPTION 2
//====================
var output_data = result.records.filter(function (el) {
return
el.price == 35;
});
I want to filter the data above using prod_name or price, or any fields combination (including id). I'd really appreciate your help with this.
CodePudding user response:
Try this:
result.records.filter(d => d.fields.product_name == "product 1");
CodePudding user response:
Its should be filter(d => d.fields.product_name == "product 1")
.
because your product_name
key is inside your fields
object of each node in the array.
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"));