Home > Software engineering >  How to select array object in API with json format
How to select array object in API with json format

Time:05-30

Im using axios to fetch product by categories using dummyjson.com api and store it to my variable name barang, but inside the json there is an array object, how to select a object inside an array object in JSON?

Code for storing data:

const [barang, setBarang] = useState([]);

useEffect(() => {
 getData();
}, []);

function getData() {
  axios.get(`https://dummyjson.com/products/category/${route.params.kategori}`).then(function (response) {
  setBarang(response.data);
 });
}

This is the data of the JSON format:

{
"products": 
[
 {
   "id": 1,
   "title": "iPhone 9",
   "category": "smartphones",
   ...
 },
 {...}
],
"total": 5,
"skip": 0,
"limit": 5
}

I can get the total with

barang.total

But the 'products' is an array object, how can i get id,title,etc from that array object??

i try to mapping only the products object using:

{
    barang.products.map((item) => {
      return (
        <Card image={item.images} key={item.id} nama={item.title} harga={item.price} stok={item.stock} kategori={item.category} description={item.description}/>
      )
    })
  }

but got error of undefined

CodePudding user response:

products is an array of objects so in order to access each one of his keys you should iterate over the products array, your last approach using map is the right one but consider that the returns of map must be added to a new variable, so you would do

let cardElement = barang.products.map((item) => { return ( <Card image={item.images} key={item.id} nama={item.title} harga={item.price} stok={item.stock} kategori={item.category} description={item.description}/> ) })

then the cardElement variable should have store all the items you need to insert

CodePudding user response:

I found a solution, this time i only put the products array object inside my 'barang' variable,

code:

function getData() {
  axios.get(`https://dummyjson.com/products/category/${route.params.kategori}`).then(function (response) {
  setBarang(response.data.product);
});
}

Now i can acces the title, price, etc with the previous mapping function

{
barang.products.map((item) => {
  return (
    <Card image={item.images} key={item.id} nama={item.title} harga={item.price} stok={item.stock} kategori={item.category} description={item.description}/>
  )
})

}

but is this the proper way?

  • Related