Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only 1st element of JSON data?

I want to fetch only 1st element of json array

my json data :

{  
 id:"1",
 price:"130000.0",
 user:55,
}
{  
  id:"2",
  price:"140000.0",
 user:55,
}

i want to access the price of 1st json element price : "13000.0"

my code

$.each(data_obj, function(index, element) {
    $('#price').append(element.price[0]);
});

but my output is '1'

like image 327
rahul.m Avatar asked Jan 02 '23 19:01

rahul.m


2 Answers

Assuming that you have array of objects

var arr = [{  
      id:"1",
      price:"130000.0",
      user:55,
     },
     {  
       id:"2",
       price:"140000.0",
      user:55,
     }]

     console.log(arr[0].price)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 125
Ali Shahbaz Avatar answered Jan 05 '23 16:01

Ali Shahbaz


You data isn't valid JSON, JSON data key must be wrap within double quote, but your data isn't wrapped in double quote

var data = [{  
    "id":"1",
    "price":"130000.0",
    "user":55
},{  
    "id":"2",
    "price":"140000.0",
    "user":55
}]

console.log(data[0]["price"]);
like image 39
Yves Kipondo Avatar answered Jan 05 '23 15:01

Yves Kipondo