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;
});
Related
I just wanted to fetch that data which coming from this https://food-ordring-af14d-default-rtdb.firebaseio.com/order the data is in the form of JSON and it looks like that
{
"-MzJLd0sSssh9tbJbjUS" : {
"orderDetails" : [ {
"amount" : 4,
"id" : "m1",
"name" : "Shushi",
"price" : 22.99
}, {
"amount" : 3,
"id" : "m2",
"name" : "Schnitzel",
"price" : 16.5
} ],
"user" : {
"address" : "A-132 shiv vihar,rishal garden,Nangloi",
"city" : "New delhi",
"name" : "Bhupender Sharma",
"postal" : "110041"
}
},
"-MzJOf_52xhRQi3izTRV" : {
"orderDetails" : [ {
"amount" : 2,
"id" : "m3",
"name" : "Barbecue Burger",
"price" : 12.99
}, {
"amount" : 2,
"id" : "m4",
"name" : "Green Bowl",
"price" : 18.99
} ],
"user" : {
"address" : "Nangloi",
"city" : "New delhi",
"name" : "ANkit",
"postal" : "445575"
}
}
}
Try this code .. here some example
const fetchdata = async()=>{
const response = await fetch('https://jsonplaceholder.typicode.com/todos')
const jdata = await response.json()
console.log(jdata)
}
fetchdata()
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 have data from mongodb like this from one collection.
/* 1 */
{
"_id" : ObjectId("5be94355f220b62c7449dc0f"),
"districts" : [
{
"name" : "NORTH AND MIDDLE",
"code" : 632.0
},
{
"name" : "EAST",
"code" : 603.0
},
{
"name" : "SOUTH",
"code" : 602.0
}
],
"state" : "ISLANDS"
}
/* 2 */
{
"_id" : ObjectId("5be94355f220b62c7441dc04"),
"districts" : [
{
"name" : "Apple",
"code" : 512.0
},
{
"name" : "Ball",
"code" : 522.0
}
],
"state" : "GOLD"
}
/* 3 */
{
"_id" : ObjectId("5eee07816a011d391a45178"),
"districts" : [
{
"name" : "DAM",
"code" : 478.0
},
{
"name" : "DEN",
"code" : 481.0
},
{
"name" : "DOG AND CAT",
"code" : 461.0
}
],
"state" : "THE NAGAR AND HAVELI"
}
I was given an excel sheet like below as shown with no other information only 2 columns
My work is to add "Short Name of District" for all districts.
I tried below method
var tc = [
"NORTH AND MIDDLE",
"EAST",
"SOUTH",
"Apple",
"Ball ",
"DAM ",
"DEN ",
"DOG AND CAT"
]
db.dummy.find({"districts.name":{$in:tc}}).forEach(x => {
x["districts"].forEach( y => {
if (
y.name == "NORTH AND MIDDLE" ){
y.short_name = "NAM"
}
if (
y.name == "EAST" ){
y.short_name = "ET"
}
if (
y.name == "SOUTH" ){
y.short_name = "ST"
}
})
})
I got the result
/* 1 */
{
"_id" : ObjectId("5be94355f220b62c7449dc0f"),
"districts" : [
{
"name" : "NORTH AND MIDDLE",
"code" : 632.0,
"short_name" : "NAM"
},
{
"name" : "EAST",
"code" : 603.0,
"short_name" : "ET"
},
{
"name" : "SOUTH",
"code" : 602.0,
"short_name" : "ST"
}
],
"state" : "ISLANDS"
}
/* 2 */
{
"_id" : ObjectId("5be94355f220b62c7441dc04"),
"districts" : [
{
"name" : "Apple",
"code" : 512.0,
"short_name" : "Al"
},
{
"name" : "Ball",
"code" : 522.0
"short_name" : "BA"
}
],
"state" : "GOLD"
}
/* 3 */
{
"_id" : ObjectId("5eee07816a011d391a45178"),
"districts" : [
{
"name" : "DAM",
"code" : 478.0,
"short_name" : "DA"
},
{
"name" : "DEN",
"code" : 481.0,
"short_name" : "DN"
},
{
"name" : "DOG AND CAT",
"code" : 461.0
"short_name" : "DAC"
}
],
"state" : "THE NAGAR AND HAVELI"
}
Is this is the only method ??
like using if loop for all districts or any other methods are there like using mongodb aggregate or any other javascript methods. It will be helpful if other methods are there as it will be problem to use if loop when there is 730 districts are there. I dont have experience in working with aggregate frameworks so i thought anyone might know other method.
You may write a mapping:
const districtNameToShort = {
'NORTH AND MIDDLE': 'NAM',
'EAST': 'ET',
...
}
Then in your forEach
const districtNameToShort = {
'NORTH AND MIDDLE': 'NAM',
'EAST': 'ET'
}
db.dummy.find().forEach(x => {
db.dummy.update(
{_id : x._id},
{$set: {
districts: x.districts.map(district => {
district.short_name = districtNameToShort[district.name] || district.name
return district
})
}}
)
})
I have this complicated object structure:
myObject = {
"myObject" : [
{
"id" : 1,
"parameters" : [
{
"name" : "name1",
"special" : "xxx"
},
{
"name" : "name2",
"special" : "yyy"
}
]
},
{
"id" : 2,
"parameters" : [
{
"name" : "name3",
"special" : "zzz"
}
]
},
{
"id" : 2,
"parameters" : [
{
"name" : "name4",
"special" : "ttt"
},
{
"name" : "name5",
"special" : "aaa"
},
{
"name" : "name6",
"special" : "zzz"
}
]
},
...
]
};
It consists of a array of other objects, each of them having a variable number of parameters.
My goal is to concatenate the special of parameters of each object into a new string which must be stored as new property of it.
In this case, the result should look like:
myObject = {
"myObject" : [
{
"id" : 1,
"parameters" : [
{
"name" : "name1",
"special" : "xxx"
},
{
"name" : "name2",
"special" : "yyy"
}
],
"newProp" : "xxxyyy"
},
{
"id" : 2,
"parameters" : [
{
"name" : "name3",
"special" : "zzz"
}
],
"newProp" : "zzz"
},
{
"id" : 2,
"parameters" : [
{
"name" : "name4",
"special" : "ttt"
},
{
"name" : "name5",
"special" : "aaa"
},
{
"name" : "name6",
"special" : "zzz"
}
],
"newProp" : "tttaaazzz"
},
...
]
};
I tried something like this:
forEach(arr in myObject.myObject){
arr.parameters(forEach (i in arr.parameters.special) {
myObject.myObject = i.concat(myObject.myObject);
})
}
obviously, it does not work. But I guess that this could be the right approach.
Any suggestions?
You can loop through the object using Array#forEach and then construct the string based on parameter values using Array#map and Array#join, like this:
const myObject = {"myObject":[{"id":1,"parameters":[{"name":"name1","special":"xxx"},{"name":"name2","special":"yyy"}]},{"id":2,"parameters":[{"name":"name3","special":"zzz"}]},{"id":2,"parameters":[{"name":"name4","special":"ttt"},{"name":"name5","special":"aaa"},{"name":"name6","special":"zzz"}]}]};
myObject.myObject.forEach(item => {
item.newProp = item.parameters.map(p => p.special).join('');
});
console.log(myObject);
Use reduce and for Each
var myObject = {
"myObject" : [
{
"id" : 1,
"parameters" : [
{
"name" : "name1",
"special" : "xxx"
},
{
"name" : "name2",
"special" : "yyy"
}
]
},
{
"id" : 2,
"parameters" : [
{
"name" : "name3",
"special" : "zzz"
}
]
},
{
"id" : 2,
"parameters" : [
{
"name" : "name4",
"special" : "ttt"
},
{
"name" : "name5",
"special" : "aaa"
},
{
"name" : "name6",
"special" : "zzz"
}
]
}
]
};
myObject.myObject.forEach(arr => {
arr.prop = arr.parameters.reduce((res,obj)=> res+obj.special, '')
})
console.log(myObject)
You can use .map() and .reduce() like this:
let myObject = [{"id" : 1, "parameters" : [{ "name" : "name1", "special" : "xxx"}, { "name" : "name2", "special" : "yyy" }]}, { "id" : 2, "parameters" : [{ "name" : "name3", "special" : "zzz"}]}, {"id" : 2, "parameters" : [{ "name" : "name4", "special" : "ttt"}, { "name" : "name5", "special" : "aaa"},{ "name" : "name6", "special" : "zzz"}]}];
let result = myObject.map(
o => (o.newProp = o['parameters'].reduce((a, o) => a + o['special'], ""), o)
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
One more way is to use nested map functions:
myObject = {"myObject":[{"id":1,"parameters":[{"name":"name1","special":"xxx"},{"name":"name2","special":"yyy"}]},{"id":2,"parameters":[{"name":"name3","special":"zzz"}]},{"id":2,"parameters":[{"name":"name4","special":"ttt"},{"name":"name5","special":"aaa"},{"name":"name6","special":"zzz"}]}]};
myObject.myObject.map(x => {
x.newProp = x.parameters.map(p => p.special).join('');
return x;
})
console.log(myObject);
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>