This question already has answers here:
Loading local JSON file
(26 answers)
Closed 7 years ago.
I have a JSON file with this as the content:
{
"residents": [
{
"name" : "Jacob",
"title" : "King",
"gender" : "Male",
},
{
"name" : "Luthor",
"title" : "Prince",
"gender" : "Male"
},
{
"name" : "Mileena",
"title" : "Princess",
"gender" : "Female"
},
]
}
I want to read the json in JavaScript, but certainly, I have no idea. How would I come about with this problem?
You can use JQuery for this.
$.ajax({
url: "\data.json", //name of your json file
success: function (data) {
var obj = JSON.parse(data);
}
});
Then you can get necessary property by the call of:
obj.residents[0].name
and so on.
It depends on environment that you use.
If you work with node.js you should read this file with API - fileRead
Then you should use JSON.parse for parsing it in {Object}
If you work in browser and some server has path to static with this file you can use ajax for getting this file
In both cases you should do such steps:
Get file as {String}
Parse to {Object}
Assuming this is for web because of your web tag, the easiest method is using jquery.
$.get('http://ip.jsontest.com', function(data) { console.log(data); });
If the server uses the correct MIME type in the response of the JSON then jquery will convert it to an object and "data" in the above example will be the evaluated JSON.
If the server does not use the correct MIME type you can wrap it in JSON.parse:
var json = JSON.parse(data);
Something like this?
$(function () {
$("#btnTest").click(function () {
var data = {
"residents": [{
"name": "Jacob",
"title": "King",
"gender": "Male",
}, {
"name": "Luthor",
"title": "Prince",
"gender": "Male"
}, {
"name": "Mileena",
"title": "Princess",
"gender": "Female"
}, ]
};
//If you're getting it somewhere from ajax call, than possibly it would be in string , in that case you need to `parse` it as data = JSON.parse(data);
$.each(data.residents, function (index, value) {
$("#data").append(value.name + " " + value.title + " " + value.gender + " </br>");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="btnTest" value="Try Me!" />
<div id="data">
</div>
Try this..
var mymessage='{
"residents": [
{
"name" : "Jacob",
"title" : "King",
"gender" : "Male",
},
{
"name" : "Luthor",
"title" : "Prince",
"gender" : "Male"
},
{
"name" : "Mileena",
"title" : "Princess",
"gender" : "Female"
},
]
}';
var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.residents.length; i++) {
var resident= jsonData.residents[i];
console.log(resident.name);
}
Using javascript you would just do...
obj = JSON.parse({
"residents": [
{
"name" : "Jacob",
"title" : "King",
"gender" : "Male",
},
{
"name" : "Luthor",
"title" : "Prince",
"gender" : "Male"
},
{
"name" : "Mileena",
"title" : "Princess",
"gender" : "Female"
},
]
});
You now have the JSON in an object that you can manage
console.log(obj);
You can fetch it like below
var text = '{
"residents":[
{
"name" : "Jacob",
"title" : "King",
"gender" : "Male",
},
{
"name" : "Luthor",
"title" : "Prince",
"gender" : "Male"
},
{
"name" : "Mileena",
"title" : "Princess",
"gender" : "Female"
},
]
}'; // That is your data from request
var obj = JSON.parse(text);
alert(obj.residents);
alert(obj.residents[0].name);
<script>
json_text = '{
"residents":[
{
"name" : "Jacob",
"title" : "King",
"gender" : "Male",
},
{
"name" : "Luthor",
"title" : "Prince",
"gender" : "Male"
},
{
"name" : "Mileena",
"title" : "Princess",
"gender" : "Female"
},
]}';
var obj = JSON.parse(json_text);
alert(obj.residents[2].name);
</script>
This code will bring up an alert dialog box in the browser with the value of name attribute of the second object in the array residents.
First and foremost your json string has error.
{
"residents": [
{
"name" : "Jacob",
"title" : "King",
"gender" : "Male",
},
{
"name" : "Luthor",
"title" : "Prince",
"gender" : "Male"
},
{
"name" : "Mileena",
"title" : "Princess",
"gender" : "Female"
},
]
}
There won't be comma after the third parenthesis from the end.
JSONString = '{ . . . . }';
JSONObject = JSON.parse(JSONString);
This way you can access the json data from JSONObject.
try this
<!docTpye html>
<html>
<head>
<script>
var data={
"residents": [
{
"name" : "Jacob",
"title" : "King",
"gender" : "Male",
},
{
"name" : "Luthor",
"title" : "Prince",
"gender" : "Male"
},
{
"name" : "Mileena",
"title" : "Princess",
"gender" : "Female"
},
]
}
for(var i=0;i<data.residents.length;i++){
console.log(data.residents[i].name);
alert(data.residents[i].name);
}
</script>
</head>
<body>
</body>
</html>
Related
I have the following sample JSON object:
var data = [ {
"id" : 1,
"name" : "Abc",
"age" : 30,
"married" : true,
"city": "ABC"
}, {
"id" : 2,
"name" : "Def",
"age" : 25,
"married" : true,
"city": "ABC"
}, {
"id" : 3,
"name" : "Pqr",
"age" : 28,
"married" : false,
"city": "ABC"
}, {
"id" : 4,
"name" : "Xyz",
"age" : 40,
"married" : true,
"city": "ABC"
} ];
I want to return true and store it in a variable if all city key values are ABC only, or else it should return false(i.e if one of city key values is not ABC) from the given JSON object. Can anyone please let me know on how to achieve this. Thanks in advance.
Using Array#every:
const data = [ { "id" : 1, "name" : "Abc", "age" : 30, "married" : true, "city": "ABC" }, { "id" : 2, "name" : "Def", "age" : 25, "married" : true, "city": "ABC" }, { "id" : 3, "name" : "Pqr", "age" : 28, "married" : false, "city": "ABC" }, { "id" : 4, "name" : "Xyz", "age" : 40, "married" : true, "city": "ABC" } ];
const valid = data.every(({ city }) => city === 'ABC');
console.log(valid);
Three possible ways of achieving this:
Using Array#every
Using Array#some
Using Array#filter
let data = [{id:1,name:"Abc",age:30,married:!0,city:"ABC"},{id:2,name:"Def",age:25,married:!0,city:"ABC"},{id:3,name:"Pqr",age:28,married:!1,city:"ABC"},{id:4,name:"Xyz",age:40,married:!0,city:"ABC"}];
console.log(data.every(({ city }) => city === "ABC"));
console.log(!data.some(({ city }) => city !== "ABC"));
console.log(!data.filter(({ city }) => city !== "ABC").length);
simply :
data.filter(x => x.city === 'ABC')
Please do a more detailed search about the problem before opening a topic.
data.some((el) => el.city !== "ABC")
I would like to use chart.js for creating a couple of charts on my webpage, now the data that I receive from the controller is in the following format,
{
"dataset" : [
{
"name" : "Sarah",
"age" : "23",
"gender" : "female",
"country" : "australia",
"occupation" : "student"
},
{
"name" : "Randy",
"age" : "19",
"gender" : "male",
"country" : "america",
"occupation" : "student"
},
{
"name" : "Roger",
"age" : "32",
"gender" : "male",
"country" : "germany",
"occupation" : "software professional"
},
{
"name" : "Maverick",
"age" : "10",
"gender" : "male",
"country" : "america",
"occupation" : "student"
},
{
"name" : "Riya",
"age" : "25",
"gender" : "female",
"country" : "australia",
"occupation" : "software professional"
},
{
"name" : "Glade",
"age" : "30",
"gender" : "female",
"country" : "India",
"occupation" : "teacher"
}
]
}
Now, I would like to plot this information on 3 pie charts,
1) pie chart that shows the count of country of origin.
2) pie chart that shows the count of occupation.
3) pie chart that shows the count of people who have age less than 25.
So ideally the graph takes in information in the following format,
var pieData = {
graph-data:
[
{
name : country,
dataset : [
{
value: america,
count: 2,
color:"#878BB6"
},
{
value: india,
count : 1,
color : "#4ACAB4"
},
{
value: germany,
count : 1,
color : "#FF8153"
},
{
value: australia,
count : 2,
color : "#FFEA88"
}
]
},
{
name : occupation,
dataset : [
{
value: "student",
count: 3,
color:"#878BB6"
},
{
value: "software professional",
count : 2,
color : "#4ACAB4"
},
{
value: "teacher",
count : 1,
color : "#FF8153"
}
]
},
{
name : "age",
dataset : [
{
value: "23",
count: 1,
color:"#878BB6"
},
{
value: "19",
count : 1,
color : "#4ACAB4"
},
{
value: "10",
count : 1,
color : "#FF8153"
},
{
value: "25",
count : 1,
color : "#FF8423"
}
]
}
]
};
As you can see from the above json, the graph-data key has 3 array elements, each of which corresponds to a chart. How can I construct this data from the initial raw dataset and pass this to my chart.js for consumption? I am guessing I would be requiring to write converters, how can I achieve this in js/jquery, any information on this is highly appreciated. Thanks ahead!
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
{
"action" : "get",
"application" : "2c5ca3b0-be74-11e4-8ff3-f7af49a474ef",
"params" : {
"ql" : [ "select * where username='pqr'" ]
},
"path" : "/logs",
"uri" : "https://api.usergrid.com/serv-d/demo1/logs",
"entities" : [ {
"uuid" : "97b0fd0a-be74-11e4-9324-b3bd8af7859e",
"type" : "log",
"created" : 1425036869840,
"modified" : 1425036869840,
"metadata" : {
"path" : "/logs/97b0fd0a-be74-11e4-9324-b3bd8af7859e"
},
"password" : "pqr",
"username" : "pqr"
}],
"timestamp" : 1425359738746,
"duration" : 15,
"organization" : "serv-d",
"applicationName" : "demo1",
"count" : 1
}
This is the server side response to my app and I want to get the user name and password values only.
Use JSON.parse() to parse the JSON response into a Javascript object. Then you can access the properties.
var obj = JSON.parse(response);
The username and password are in an array that's in the entities property, so you can access them as:
var username = obj.entities[0].username;
var password = obj.entities[0].password;
Get the data in a variable, say in variable data.
var data = {
"action" : "get",
"application" : "2c5ca3b0-be74-11e4-8ff3-f7af49a474ef",
"params" : {
"ql" : [ "select * where username='pqr'" ]
},
"path" : "/logs",
"uri" : "https://api.usergrid.com/serv-d/demo1/logs",
"entities" : [ {
"uuid" : "97b0fd0a-be74-11e4-9324-b3bd8af7859e",
"type" : "log",
"created" : 1425036869840,
"modified" : 1425036869840,
"metadata" : {
"path" : "/logs/97b0fd0a-be74-11e4-9324-b3bd8af7859e"
},
"password" : "pqr",
"username" : "pqr"
}],
"timestamp" : 1425359738746,
"duration" : 15,
"organization" : "serv-d",
"applicationName" : "demo1",
"count" : 1
};
//logging username and password fields
console.log(data.entities[0].username, data.entities[0].password);
JSON behaves like key value pair kind of collection. Assign this Json to Javascript variable and then you can get the values of JSON with respective key like
var myJson =
{
"action" : "get", "application" : "2c5ca3b0-be74-11e4-8ff3-
f7af49a474ef", "params" : { "ql" : [ "select * where
username='pqr'" ] }, "path" : "/logs", "uri" :
"https://api.usergrid.com/serv-d/demo1/logs", "entities" : [
{ "uuid" : "97b0fd0a-be74-11e4-9324-b3bd8af7859e", "type" :
"log", "created" : 1425036869840, "modified" :
1425036869840, "metadata" :
{ "path" : "/logs/97b0fd0a-be74-11e4-9324-b3bd8af7859e"
}, "pas sword" : "pqr", "username" : "pqr"
}], "timestamp" : 1425359738746, "duration" : 15,
"organization" : "serv-d", "applicationName" : "demo1",
"count" : 1 };
var action = myJSON.action;
var uri = myJSON.uri; and so on..
Assuming you store it as "obj", then you can do obj.entities[0].username (and likewise for password.
Assuming you are referring it as data, You can use data.entities[0].username to access username.
var data = {
"action": "get",
"application": "2c5ca3b0-be74-11e4-8ff3-f7af49a474ef",
"params": {
"ql": [
"select * where username='pqr'"
]
},
"path": "/logs",
"uri": "https://api.usergrid.com/serv-d/demo1/logs",
"entities": [
{
"uuid": "97b0fd0a-be74-11e4-9324-b3bd8af7859e",
"type": "log",
"created": 1425036869840,
"modified": 1425036869840,
"metadata": {
"path": "/logs/97b0fd0a-be74-11e4-9324-b3bd8af7859e"
},
"password": "pqr",
"username": "pqr"
}
],
"timestamp": 1425359738746,
"duration": 15,
"organization": "serv-d",
"applicationName": "demo1",
"count": 1
};
alert(data.entities[0].username)
alert(data.entities[0].password)
var yourData = {
"action" : "get",
"application" : "2c5ca3b0-be74-11e4-8ff3-f7af49a474ef",
"params" : {
"ql" : [ "select * where username='pqr'" ]
},
"path" : "/logs",
"uri" : "https://api.usergrid.com/serv-d/demo1/logs",
"entities" : [ {
"uuid" : "97b0fd0a-be74-11e4-9324-b3bd8af7859e",
"type" : "log",
"created" : 1425036869840,
"modified" : 1425036869840,
"metadata" : {
"path" : "/logs/97b0fd0a-be74-11e4-9324-b3bd8af7859e"
},
"password" : "pqr",
"username" : "pqr"
}],
"timestamp" : 1425359738746,
"duration" : 15,
"organization" : "serv-d",
"applicationName" : "demo1",
"count" : 1
}
Because username and password is data of entities- that is an array of one element member
you may access the username data
var username = yourData.entities[0].username
Similarly for password
We have a mongo collection messages that is in the following format...
/* 0 */
{
"text" : "A message to John",
"created" : ISODate("2015-01-29T23:50:10.488Z"),
"to" : {
"id" : ObjectId("54bf1dc6c65b030c00faec0d"),
"name" : "John Smith"
},
"from" : {
"id" : ObjectId("54bf1e1ceb5bf8800b0f5a8c"),
"name" : "Martin Fowler"
},
}
/* 1 */
{
"text" : "Another message to John",
"created" : ISODate("2015-01-30T00:37:38.106Z"),
"to" : {
"id" : ObjectId("54bf1dc6c65b030c00faec0d"),
"name" : "John Smith"
},
"from" : {
"id" : ObjectId("54bf1e1ceb5bf8800b0f5a8c"),
"name" : "Martin fowler"
},
}
/* 2 */
{
"text" : "Just another message to Jerry",
"created" : ISODate("2015-01-30T00:37:38.106Z"),
"to" : {
"id" : ObjectId("54bf1e80eb5bf8800b0f5a8d"),
"name" : "Jerry Jones"
},
"from" : {
"id" : ObjectId("54bf1e1ceb5bf8800b0f5a8c"),
"name" : "Martin Fowler"
},
}
/* 2 */
{
"text" : "Message to Martin Fowler",
"created" : ISODate("2015-01-30T00:37:38.106Z"),
"to" : {
"id" : ObjectId("54bf1e80eb5bf8800b0f5a8d"),
"name" : "Martin Fowler"
},
"from" : {
"id" : ObjectId("54bf1e1ceb5bf8800b0f5a8c"),
"name" : "Jerry Jones"
},
}
We need to display the data above in a conversation format where we group each of the conversations together. A conversation meaning that it can either be to or from.
An example of what we need this to data to look like is the following format:
{
"result":[
{
"id":"54bf1dc6c65b030c00faec0d",
"name":"Jerry Jones",
"messages":[
{
"text" : "A message to John",
"created" : ISODate("2015-01-29T23:50:10.488Z"),
"to" : {
"id" : ObjectId("54bf1dc6c65b030c00faec0d"),
"name" : "John Smith"
},
"from" : {
"id" : ObjectId("54bf1e1ceb5bf8800b0f5a8c"),
"name" : "Martin Fowler"
},
}
{
"text" : "Another message to John",
"created" : ISODate("2015-01-30T00:37:38.106Z"),
"to" : {
"id" : ObjectId("54bf1dc6c65b030c00faec0d"),
"name" : "John Smith"
},
"from" : {
"id" : ObjectId("54bf1e1ceb5bf8800b0f5a8c"),
"name" : "Martin fowler"
},
}
]
},
{
"id":"54bf1e80eb5bf8800b0f5a8d",
"name":"John Smith",
"messages":[
{
"text" : "Just another message to Jerry",
"created" : ISODate("2015-01-30T00:37:38.106Z"),
"to" : {
"id" : ObjectId("54bf1e80eb5bf8800b0f5a8d"),
"name" : "Jerry Jones"
},
"from" : {
"id" : ObjectId("54bf1e1ceb5bf8800b0f5a8c"),
"name" : "Martin Fowler"
},
}
{
"text" : "Message to Martin Fowler",
"created" : ISODate("2015-01-30T00:37:38.106Z"),
"to" : {
"id" : ObjectId("54bf1e80eb5bf8800b0f5a8d"),
"name" : "Martin Fowler"
},
"from" : {
"id" : ObjectId("54bf1e1ceb5bf8800b0f5a8c"),
"name" : "Jerry Jones"
},
}
]
}
]
}
NOTE This query is always made in the context of a current user which is why on each of the conversations, we have an _id and a name which represents the other user in the conversation. For the example above, the current user would be Martin Fowler
We have tried several different ways of accomplishing this, but keep running into issues. Id rather turn to the Mongo/Node community in order to see how it can be done correctly. We are using mongoose with Node if that helps at all...
The initial query implementation that we have currently is the following:
Message.find().or([{'from.id':req.user.id},{'to.id':req.user.id}]).exec(function(err,messages){
//NEED TO IMPLEMENT THIS HERE CORRECTLY
});
NOTE that the req.user.id is the id of the current user
This solution is a slight modification of my previous solution to a similar kind of problem here.
The documents in question have member names in inconsistent cases. Martin Folwer should be Martin Fowler throughout the app/database, and not Martin fowler. (Note the small f). You need to make this change to your documents.
$group messages together, based on the to and from field.
construct a group key - "message_between", with the value being a
$concat result of the values in to and from fields.
Messages from Martin Fowler to Jerry Jones and Jerry Jones to
Martin Fowler should be treated under a single group.To achieve
that, we make the result contain the name coming last
alphabetically, first. So our key for all the Messages from Martin
Fowler to Jerry Jones and Jerry Jones to Martin Fowler would be
Martin Fowler and Jerry Jones.
Code:
Model.aggregate(
//match all those records which involve the user.
{$match:{$or:[{"to.name":req.user.id},
{"from.name":req.user.id}]}},
{$group:{"_id":{
"message_between":{
$cond:[
{
$gt:[
{$substr:["$to.name",0,1]},
{$substr:["$from.name",0,1]}]
},
{$concat:["$to.name"," and ","$from.name"]},
{$concat:["$from.name"," and ","$to.name"]}
]
},"name":{$cond:[{$eq:["$to.name",
req.user.id]},
"$from.name",
"$to.name"]}
},"messages":{$push:"$$ROOT"}
}
},
{$project:{"_id":0,"name":"$_id.name","messages":1}}
,function(err,resp){
// handle response.
})
o/p:
{
"messages" : [
{
"_id" : ObjectId("54d1d819b62f332e93fbb906"),
"text" : "Just another message to Jerry",
"created" : ISODate("2015-01-30T00:37:38.106Z"),
"to" : {
"id" : ObjectId("54bf1e80eb5bf8800b0f5a8d"),
"name" : "Jerry Jones"
},
"from" : {
"id" : ObjectId("54bf1e1ceb5bf8800b0f5a8c"),
"name" : "Martin Fowler"
}
},
{
"_id" : ObjectId("54d1d819b62f332e93fbb907"),
"text" : "Message to Martin Fowler",
"created" : ISODate("2015-01-30T00:37:38.106Z"),
"to" : {
"id" : ObjectId("54bf1e80eb5bf8800b0f5a8d"),
"name" : "Martin Fowler"
},
"from" : {
"id" : ObjectId("54bf1e1ceb5bf8800b0f5a8c"),
"name" : "Jerry Jones"
}
}
],
"name" : "Jerry Jones"
}
{
"messages" : [
{
"_id" : ObjectId("54d1d819b62f332e93fbb904"),
"text" : "A message to John",
"created" : ISODate("2015-01-29T23:50:10.488Z"),
"to" : {
"id" : ObjectId("54bf1dc6c65b030c00faec0d"),
"name" : "John Smith"
},
"from" : {
"id" : ObjectId("54bf1e1ceb5bf8800b0f5a8c"),
"name" : "Martin Fowler"
}
},
{
"_id" : ObjectId("54d1d819b62f332e93fbb905"),
"text" : "Another message to John",
"created" : ISODate("2015-01-30T00:37:38.106Z"),
"to" : {
"id" : ObjectId("54bf1dc6c65b030c00faec0d"),
"name" : "John Smith"
},
"from" : {
"id" : ObjectId("54bf1e1ceb5bf8800b0f5a8c"),
"name" : "Martin Fowler"
}
}
],
"name" : "John Smith"
}
I tried to create a mongo request for you, but i'm not sure it's relevant...
I can generate almost exactly the same format as you need in one request:
db.messages.aggregate([{$match:{$or:[{"from.id":ObjectId("54bf1dc6c65b030c00faec0d")},{"to.id":ObjectId("54bf1dc6c65b030c00faec0d")}]}},{$group:{_id: ObjectId("54bf1dc6c65b030c00faec0d"), messages:{$push: "$$ROOT"}}}]);
The probleme is, you still need to specify the id, i'm not sure it's what you need.
Using this I get the following result:
{
"_id": ObjectId("54bf1dc6c65b030c00faec0d"),
"messages": [
{
"_id": ObjectId("54d1b9f02cd45cae7e453633"),
"text": "A message to John",
"created": ISODate("2015-01-29T23:50:10.488Z"),
"to": {
"id": ObjectId("54bf1dc6c65b030c00faec0d"),
"name": "John Smith"
},
"from": {
"id": ObjectId("54bf1e1ceb5bf8800b0f5a8c"),
"name": "Martin Fowler"
}
},
{
"_id": ObjectId("54d1ba052cd45cae7e453634"),
"text": "Another message to John",
"created": ISODate("2015-01-30T00:37:38.106Z"),
"to": {
"id": ObjectId("54bf1dc6c65b030c00faec0d"),
"name": "John Smith"
},
"from": {
"id": ObjectId("54bf1e1ceb5bf8800b0f5a8c"),
"name": "Martin fowler"
}
}
]
}
I'm not using mongoose so I can't help you with this part, but with "mongodb" module, this query can be used directly, so it should be possible with mongoose too.
This is the JSON Array what Iam getting:
[
{
"Name" : "Sachin",
"Age" : "41",
"Team" : "Mumbai"
},
{
"Name" : "Dravid",
"Age" : "42",
"Team" : "Rajasthan"
},
{
"Name" : "Yuvraj",
"Age" : "31",
"Team" : "Bangalore"
}
]
But I need to sort this JSON array desc by the "Age" attribute.
My desired JSON Array should be like below:
[
{
"Name" : "Dravid",
"Age" : "42",
"Team" : "Rajasthan"
},
{
"Name" : "Sachin",
"Age" : "41",
"Team" : "Mumbai"
},
{
"Name" : "Yuvraj",
"Age" : "31",
"Team" : "Bangalore"
}
]
How to achieve this?
var a = [
{
"Name" : "Sachin",
"Age" : "41",
"Team" : "Mumbai"
},
{
"Name" : "Dravid",
"Age" : "42",
"Team" : "Rajasthan"
},
{
"Name" : "Yuvraj",
"Age" : "31",
"Team" : "Bangalore"
}
];
a.sort(function(x,y){return y["Age"]-x["Age"]});
console.log(a);
Use the following generic function predicateBy to sort your data by the desired field
var data=[
{
"Name" : "Sachin",
"Age" : "41",
"Team" : "Mumbai"
},
{
"Name" : "Dravid",
"Age" : "42",
"Team" : "Rajasthan"
},
{
"Name" : "Yuvraj",
"Age" : "31",
"Team" : "Bangalore"
}
]
function predicatBy(prop){
return function(a,b){
if( a[prop] > b[prop]){
return 1;
}else if( a[prop] < b[prop] ){
return -1;
}
return 0;
}
}
//Usage
data.sort( predicatBy("age") );
console.log(data);
var _ = require('underscore');
var data = ...your data...
console.log(_.sortBy(data, 'Age').reverse());
The naive answer would be to use Array.prototype.sort([compareFunction]). Something in the way of:
function compareAgeProperty(a,b) {
return (parseInt(a.Age) < parseInt(b.Age)) ? -1 : 1;
}
var arr = [/* your array's data here */];
arr.sort(compareAgeProperty);
I'd recommend you take a look at:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Your Age property is a string, and thus compared as a string, meaning '80'<'9'===true. Parsing the property should solve this issue.
Try this:
var arr = [
{
"Name" : "Sachin",
"Age" : "41",
"Team" : "Mumbai"
},
{
"Name" : "Dravid",
"Age" : "42",
"Team" : "Rajasthan"
},
{
"Name" : "Yuvraj",
"Age" : "31",
"Team" : "Bangalore"
}
]
var prop = "Age"
arr.sort(function(a,b){
var cmp = -1
if (a.hasOwnProperty(prop) && b.hasOwnProperty(prop)){
var a_prop_value = parseFloat(a[prop])
var b_prop_value = parseFloat(b[prop])
if (isNaN(a_prop_value) || isNaN(b_prop_value)){
//string comp
cmp = a[prop].localeCompare(b[prop])
}else{
cmp = a_prop_value - b_prop_value > 0? 1 : a_prop_value - b_prop_value ==0? 0:-1
}
}
return cmp;
});