Reputation: 5854
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'
Upvotes: 4
Views: 31807
Reputation: 5603
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"]);
Upvotes: 3
Reputation: 5854
Following is the solution worked for my problem I use return false;
$.each(data_obj, function(index, element) {
$('#price').append(element.price[0]);
return false;
});
Which gives only 1st value of array elements.
Upvotes: 0
Reputation: 323
Hello You just need to add [] from starting and ending point of your json string. see here var data = JSON.parse( '[{ "id":"1","price":"130000.0","user":55},{"id":"2","price":"140000.0","user":55}]');
var priceValue = 0;
$.each(data, function(index, element) {if(index == 0){ priceValue = element.price;}});console.log(priceValue);
Your answer will be 13000.0
Upvotes: 1
Reputation: 350
If you want only the first item's price, you don't need a loop here.
$('#price').append(data_obj[0].price);
would work here.
For further reading you can refer here
Upvotes: 0
Reputation: 51
var my_first_json_obj = data_obj[0]; // Your first JSON obj (if it's an array of json object)
var my_price = my_first_json_obj.price; // Your price
$('#price').append(my_price);
Upvotes: 0
Reputation: 909
You are using for each loop and in function you get 2 params first one is index and second is the element itself. So this will iterate through all elements.
$.each(data_obj, function(index, element) {
$('#price').append(element.price);
});
If you just want to get first element
$('#price').append(data_obj[0].price);
Upvotes: 0
Reputation: 845
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>
Upvotes: 4
Reputation: 482
The element having the your JSON data means, we can able to use below code to get the first JSON data.
element[0].price
Thanks,
Upvotes: 0