Home > Software engineering >  json filtering javascript api
json filtering javascript api

Time:11-26

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();

CodePudding user response:

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));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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)
}
  • Related