0

I have this code

var obj = [];
$('#next').click(function(){
  jQuery.getJSON(produk1 , function(product1) {
    hargana1 = product1.price;
    obj.push({
       harga: hargana1
    });
  }

  jQuery.getJSON(produk2 , function(product1) {
    hargana2 = product2.price;
    obj.push({
       harga: hargana2
    });
  }

  console.log(harga)
});

And I have result on my console like this

console

How can I get value from harga? I try with obj['harga'] It shows undefined

3
  • 3
    That's an array, not object. Try obj[0].harga. Commented Apr 22, 2020 at 8:18
  • Does this answer your question? can't access JavaScript array values by index Commented Apr 22, 2020 at 8:47
  • It's showing Cannot read property 'harga' of undefined when I try to obj.lenght, it's showing undefined, I think I have weird format of my array Commented Apr 22, 2020 at 9:31

2 Answers 2

2

Well if you take a closer look then you will see that this is actually an array filled with objects. you can see that its an array by the brackets []

Try it like this: obj[0].harga

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

2 Comments

It's showing Cannot read property 'harga' of undefined when I try to obj.lenght, it's showing undefined, I think I have weird format of my array
could you show us some code? with just the data i can not help you
1

You should iterate through the array :

const out = [{harga:21132424},{harga:543535}]
console.log(out)

out.forEach(obj=>{
     const harga = obj.harga;
     //do something to harga here
     console.log(harga)
})

Comments

Your Answer

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