简体   繁体   中英

json filtering javascript api

Hello i have some problem with json filtration when i print jsonArray without id (jsonArray) prints the object to me normally but when i add.id (jsonArray.id) its says undefined What am I doing wrong?

the object i gets with jsonArray and i want to print only 'id' of it {id: 39497866969165, product_id: 6677529493581, title: '8', price: '181.50'}

const api_url= 'https://eu.kith.com/collections/kith-mlb-for-clarks-originals/products/ck26166616.json'
async function getID() {
const response = await fetch(api_url);
const data = await response.json();
const findsize = data.product.variants
const jsonArray = findsize.filter(function(ele){
return ele.title == "8";
});

console.log(jsonArray.id)
}
getID();

jsonArray is array not object. And getID is a async function. It will return promise. You need to call then to get result.

 const api_url = 'https://eu.kith.com/collections/kith-mlb-for-clarks-originals/products/ck26166616.json' async function getID() { const response = await fetch(api_url); const data = await response.json(); const findsize = data.product.variants const jsonArray = findsize.filter(function(ele) { return ele.title == "8"; }); const tmp_obj = { id: jsonArray[0].id, product_id: jsonArray[0].product_id, title: jsonArray[0].title, price: jsonArray[0].price } //console.log(tmp_obj) return tmp_obj } getID().then(result => console.log(result));

It's because jsonArray here is a list and not a single object.

First check it's length to make sure there's atleast one object after the filter and log the first element via:

if (jsonArray.length > 0) {
    console.log(jsonArray[0].id)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM