2

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();
1
  • jsonArray is an array of objects. you need to access the id of the particular array element e.g. the first with jsonArray[0].id Commented Nov 25, 2021 at 13:56

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.