javascript for loop through nested json values - javascript

I am trying to loop through a json file for all the total and first_record values. The key is
json.STATION[0].OBSERVATIONS.precipitation[0].total
I'm trying to return a result:
[20180116, 0.8], [20180117, 0.0] . . .
I've tried a variety of approaches. My best result has been the classic undefined
Below is a snippet from the jsfiddle I have been working on. The json is generated by mesowest.net api.
Once I have this sorted out I am hoping to plot the values in highcharts. thanks.
const data = {
"UNITS": {
"precipitation": "Inches"
},
"STATION": [{
"STATUS": "ACTIVE",
"MNET_ID": "25",
"PERIOD_OF_RECORD": {
"start": "20000120",
"end": "20180121"
},
"ELEVATION": "6340",
"NAME": "BOGUS BASIN",
"RESTRICTED": false,
"STID": "BOGI1",
"ELEV_DEM": "6362",
"LONGITUDE": "-116.09685",
"STATE": "ID",
"OBSERVATIONS": {
"precipitation": [{
"count": 23,
"first_report": "20180115",
"interval": 1,
"report_type": "precip_accum",
"last_report": "20180115",
"total": 0.0
}, {
"count": 24,
"first_report": "20180116",
"interval": 2,
"report_type": "precip_accum",
"last_report": "20180116",
"total": 0.2
}, {
"count": 24,
"first_report": "20180117",
"interval": 3,
"report_type": "precip_accum",
"last_report": "20180117",
"total": 0.0
}, {
"count": 24,
"first_report": "20180118",
"interval": 4,
"report_type": "precip_accum",
"last_report": "20180118",
"total": 0.0
}, {
"count": 24,
"first_report": "20180119",
"interval": 5,
"report_type": "precip_accum",
"last_report": "20180119",
"total": 0.8
}, {
"count": 24,
"first_report": "20180120",
"interval": 6,
"report_type": "precip_accum",
"last_report": "20180120",
"total": 0.0
}, {
"count": 13,
"first_report": "20180121",
"interval": 7,
"report_type": "precip_accum",
"last_report": "20180121",
"total": 0.0
}]
},
"LATITUDE": "43.76377",
"TIMEZONE": "America\/Boise",
"ID": "1160"
}],
"SUMMARY": {
"DATA_QUERY_TIME": 1.6429424286,
"RESPONSE_CODE": 1,
"RESPONSE_MESSAGE": "OK",
"METADATA_RESPONSE_TIME": "0.0920295715332 ms",
"NUMBER_OF_OBJECTS": 1,
"PRECIP_DATA_TIME": 2.4950504303,
"DATA_PARSE_TIME": 0.8418560028
}
};
console.log(data.STATION[0].OBSERVATIONS.precipitation[4].total);
document.getElementById("demo").innerHTML = data.STATION[0].OBSERVATIONS.precipitation[4].total;
const totl = data.STATION[0].OBSERVATIONS.precipitation[0].total;
console.log(totl);
//
var i, precipitation;
for (i = 0; i < data.STATION[0].OBSERVATIONS.precipitation.total.length; i++) {
precip = data.STATION[0].OBSERVATIONS.precipitation[i].total;
}
console.log(precip);
//console.log(obj);
<p id="demo"></p>

First off, in your for loop you are referring to data.STATION[0].OBSERVATIONS.precipitation.total.length, but the total part isn't even defined there. It's have to be precipitation[0].total for it to be anything, and even then, it isn't an array. You just want:
data.STATION[0].OBSERVATIONS.precipitation.length
Also, just code-style wise, stick that into a variable so you don't have to type that craziness over and over. It'll also help avoid typos:
const records = data.STATION[0].OBSERVATIONS.precipitation;
You also are just setting the same value back to a variable over and over, so at the end, you'd only have the last value. You want to stick them in an array.
const totals = [];
for (let i = 0; i < records.length; i++) {
totals.push(records[i].total);
}
If you want both total and first_report, you can either do parallel arrays:
const totals = [];
const firsts = [];
for (let i = 0; i < records.length; i++) {
totals.push(records[i].total);
firsts.push(records[i].first_record);
}
or have an array of arrays:
const results = [];
for (let i = 0; i < records.length; i++) {
results.push([records[i].total, records[i].first_record]);
}
Here is a working example:
const data = {
"UNITS": {
"precipitation": "Inches"
},
"STATION": [{
"STATUS": "ACTIVE",
"MNET_ID": "25",
"PERIOD_OF_RECORD": {
"start": "20000120",
"end": "20180121"
},
"ELEVATION": "6340",
"NAME": "BOGUS BASIN",
"RESTRICTED": false,
"STID": "BOGI1",
"ELEV_DEM": "6362",
"LONGITUDE": "-116.09685",
"STATE": "ID",
"OBSERVATIONS": {
"precipitation": [{
"count": 23,
"first_report": "20180115",
"interval": 1,
"report_type": "precip_accum",
"last_report": "20180115",
"total": 0.0
}, {
"count": 24,
"first_report": "20180116",
"interval": 2,
"report_type": "precip_accum",
"last_report": "20180116",
"total": 0.2
}, {
"count": 24,
"first_report": "20180117",
"interval": 3,
"report_type": "precip_accum",
"last_report": "20180117",
"total": 0.0
}, {
"count": 24,
"first_report": "20180118",
"interval": 4,
"report_type": "precip_accum",
"last_report": "20180118",
"total": 0.0
}, {
"count": 24,
"first_report": "20180119",
"interval": 5,
"report_type": "precip_accum",
"last_report": "20180119",
"total": 0.8
}, {
"count": 24,
"first_report": "20180120",
"interval": 6,
"report_type": "precip_accum",
"last_report": "20180120",
"total": 0.0
}, {
"count": 13,
"first_report": "20180121",
"interval": 7,
"report_type": "precip_accum",
"last_report": "20180121",
"total": 0.0
}]
},
"LATITUDE": "43.76377",
"TIMEZONE": "America\/Boise",
"ID": "1160"
}],
"SUMMARY": {
"DATA_QUERY_TIME": 1.6429424286,
"RESPONSE_CODE": 1,
"RESPONSE_MESSAGE": "OK",
"METADATA_RESPONSE_TIME": "0.0920295715332 ms",
"NUMBER_OF_OBJECTS": 1,
"PRECIP_DATA_TIME": 2.4950504303,
"DATA_PARSE_TIME": 0.8418560028
}
};
const records = data.STATION[0].OBSERVATIONS.precipitation;
const results = [];
for (let i = 0; i < records.length; i++) {
results.push([records[i].total, records[i].first_report]);
}
console.log(results);

FWIW, your key is not precipitation[0] but you want to iterate through all precipitation elements:
// precipitation is an array, so it supports Array.prototype.map()
var output = data.STATION[0].OBSERVATIONS.precipitation.map(function(p) {
return [p.first_report, p.total] });
see also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Related

Retrive Value from nested object using recursion

I have an JS object data, from this array of object, I need to take "amount" value which is inside of "limitBreakup" Array. I have done using .map(), But I am intersted to know the implementation of the same using Recursion.
var data = [
{
"limitRequirementId":"123",
"facilityType":"cc",
"amount":800000,
"existingRoi":12,
"existingPf":12100,
"repoRate":5,
"spread":10,
"tenure":24,
"margin":10000,
"loanVariable":{
"type":"roi/commission",
"value":15
},
"limitBreakup":[
{
"limitRequirementId":"13",
"facilityType":"cc",
"repoRate":5,
"amount":8000,
"spread":10,
"tenure":24,
"margin":100,
"loanVariable":{
"type":"roi/commission",
"value":15
}
},
{
"limitRequirementId":"22",
"facilityType":"LC",
"repoRate":4,
"amount":900,
"spread":6,
"tenure":21,
"margin":15,
"loanVariable":{
"type":"roi/commission",
"value":10
}
}
]
},
{
"limitRequirementUniqueId":"13",
"limitRequirementId":"13",
"facilityType":"lc",
"amount":900000,
"existingRoi":10,
"existingPf":1000,
"repoRate":3,
"spread":1,
"tenure":21,
"margin":1000,
"loanVariable":{
"type":"roi/commission",
"value":15
},
"limitBreakup":[
{
"limitRequirementId":"35",
"facilityType":"CC",
"repoRate":6,
"amount":600,
"spread":8,
"tenure":28,
"margin":13,
"loanVariable":{
"type":"roi/commission",
"value":14
}
}
]
}
]
My Solution using normal iteration works:
data.forEach((d, i)=>{
let limitBreakup = d.limitBreakup;
if(Array.isArray(limitBreakup)){
limitBreakup.forEach((l)=>{ console.log(l, '->', l.amount) })
}else{
console.log(limitBreakup, 'else->', limitBreakup.amount)
}
//console.log(d.limitBreakup);
})
But using Recursion, I am half way:
https://jsfiddle.net/1g98sLw3/2/
http://www.mocky.io/v2/5ea974eb3400005e003f0203 (Since the json object is very big, I have pasted in mocky.io for reference)
Something like this should work
Demo proof: https://jsfiddle.net/do58kj3q/
You need a loop to pass through your objects and then add them to the array when you meet the criteria
var data = [{
"limitRequirementId": "123",
"facilityType": "cc",
"amount": 800000,
"existingRoi": 12,
"existingPf": 12100,
"repoRate": 5,
"spread": 10,
"tenure": 24,
"margin": 10000,
"loanVariable": {
"type": "roi/commission",
"value": 15
},
"limitBreakup": [{
"limitRequirementId": "13",
"facilityType": "cc",
"repoRate": 5,
"amount": 8000,
"spread": 10,
"tenure": 24,
"margin": 100,
"loanVariable": {
"type": "roi/commission",
"value": 15
}
},
{
"limitRequirementId": "22",
"facilityType": "LC",
"repoRate": 4,
"amount": 900,
"spread": 6,
"tenure": 21,
"margin": 15,
"loanVariable": {
"type": "roi/commission",
"value": 10
}
}
]
},
{
"limitRequirementUniqueId": "13",
"limitRequirementId": "13",
"facilityType": "lc",
"amount": 900000,
"existingRoi": 10,
"existingPf": 1000,
"repoRate": 3,
"spread": 1,
"tenure": 21,
"margin": 1000,
"loanVariable": {
"type": "roi/commission",
"value": 15
},
"limitBreakup": [{
"limitRequirementId": "35",
"facilityType": "CC",
"repoRate": 6,
"amount": 600,
"spread": 8,
"tenure": 28,
"margin": 13,
"loanVariable": {
"type": "roi/commission",
"value": 14
}
}]
}
]
var array=[];
function recursiveCounter(arr) {
for (let i = 0; i < arr.length; i++) {
const obj = arr[i];
if (!obj.limitBreakup) {
array.push(obj.amount);
}
if (Array.isArray(obj.limitBreakup)) {
recursiveCounter((obj.limitBreakup));
}
}
}
recursiveCounter(data);
console.log(array)

How to turn object values into new array in JavaScript

I am trying to simplify the following state:
{
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types": [
{
"slot": 1,
"type": {
"name": "poison",
"url": "https://poke"
}
},
{
"slot": 2,
"type": {
"name": "grass",
"url": "https://poke"
}
}
]}
into something like this:
{
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types": [ "poison", "grass" ]
}
Also, I would like to mention that I have an array with 151 of these. Not every object contains two types; some only contain one.
I believe that is the reason most of what I have tried so far does not work. Thank you in advance for your help.
Try using map
let obj={ name: "bulbasaur", picture: "https://raw", height: 7, weight: 69, types : [{ slot: 1, type: { name: "poison", url:"https://poke" }}]};
obj.types=obj.types.map( Type => Type.type.name);
console.log(obj.types);
I think this is what you want, you will need to add this snippet in a loop for you dataset and have it pushed into a new array:
const Obj = {
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types" : [{
"slot": 1,
"type": {
"name": "poison",
"url":"https://poke"
}}, {
"slot": 2,
"type": {
"name": "grass",
"url":"https://poke"
}}
]};
const newObj = {
...Obj,
types: Obj.types.map((el) => el.type.name),
}
console.log(newObj)
I was able to resolve what I needed by using the logic provided by Ma'moun othman.
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types" : [{
"slot": 1,
"type": {
"name": "poison",
"url":"https://poke"
}}, {
"slot": 2,
"type": {
"name": "grass",
"url":"https://poke"
}}
]};
const newObj = {
...Obj,
types: Obj.types.map((el) => el.type.name),
}
console.log(newObj)

Push data to array without using if statement

I have following output. it gives my API.
{
"_id": {
"year": 2018,
"month": 6,
"day": 11,
"hour": 12,
"interval": 45,
"method": "200"
},
"count": 1
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 16,
"interval": 50,
"method": "404"
},
"count": 5
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 17,
"interval": 10,
"method": "200"
},
"count": 47
}}
I want to Push them to arrays according to method. As an example
twoHundArray=[
{ "x":2018,6,11,12,45,
"y" :1},
{"x": 2016,11,11,17,10 ,
"y" :47}]
fourhundrArry=[{ "x":2018,11,11,16,50,
"y" :5}]
without using if/else statement how to push them to different arrays. In here I don't know all the names of methods.so cannot use if statement for "method".that is the problem here.
The original object is invalid. You can't have elements in an object without specifying the keys. I've assumed that it is an array.
Secondly, there is no way of pushing elements to different arrays without knowing their names. So the judgement of pushing the elements to different variables will have to be based on if/else conditions. Additionally, creation of those variables will vary based on the groups, as method could have been any value.
If you agree to group the objects based on the values method have, here is a way to do this:
const data = [{"_id":{"year":2018,"month":6,"day":11,"hour":12,"interval":45,"method":"200"},"count":1},{"_id":{"year":2016,"month":11,"day":11,"hour":16,"interval":50,"method":"404"},"count":5},{"_id":{"year":2016,"month":11,"day":11,"hour":17,"interval":10,"method":"200"},"count":47}];
const res = {};
data.forEach(item => {
const { method, ...obj } = item['_id'];
res[method] = res[method] || [];
res[method].push({
x: Object.values(obj),
y: item.count
});
});
console.log(res);
It creates an object, whose keys are method. The values in the object are the arrays, which contain the items grouped by method.
You can use Array.reduce and create a map based on method. Try the following:
var data = [{
"_id": {
"year": 2018,
"month": 6,
"day": 11,
"hour": 12,
"interval": 45,
"method": "200"
},
"count": 1
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 16,
"interval": 50,
"method": "404"
},
"count": 5
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 17,
"interval": 10,
"method": "200"
},
"count": 47
}];
var method = data.reduce((a,o)=>{
if(!a[o._id.method]){
a[o._id.method] = [];
};
var { method, ...ob } = o._id;
a[o._id.method].push({
"x": Object.values(ob).join(","),
"y" : o.count
});
return a;
}, {});
console.log(method);
You can create an object with status:values key/pair using Array.reduce and post that using Object destructuring and default assignment, create independent variables.
const arr = [{"_id":{"year":2018,"month":6,"day":11,"hour":12,"interval":45,"method":"200"},"count":1},{"_id":{"year":2016,"month":11,"day":11,"hour":16,"interval":50,"method":"404"},"count":5},{"_id":{"year":2016,"month":11,"day":11,"hour":17,"interval":10,"method":"200"},"count":47}];
let obj = arr.reduce((a,c) => {
a[c._id.method] = a[c._id.method] || [];
a[c._id.method].push({"x" : Object.values(c._id).join(), "y" : c.count});
return a;
},{});
/* You can add an entry here for every status type, it will pick the
** value from object and if not present will be defaulted to an empty array */
const {200 : twoHundArray=[], 404 : fourHundArray=[], 300 : threeHundArray=[]} = obj;
console.log(twoHundArray);
console.log(fourHundArray);
console.log(threeHundArray);
#Palani, I'll suggest you to use an object to gather all the required information.
Please have a look at the below code and let me know any suggestions/modifications if you need.
var timeDataArr = [
{
"_id": {
"year": 2018,
"month": 6,
"day": 11,
"hour": 12,
"interval": 45,
"method": "200"
},
"count": 1
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 16,
"interval": 50,
"method": "404"
},
"count": 5
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 17,
"interval": 10,
"method": "200"
},
"count": 47
}
]
// An object that maps 'method' to its related data array
var newTimeData = {}
for(var timeData of timeDataArr) {
var obj = timeData["_id"];
var arr = [obj["year"], obj["month"], obj["day"], obj["hour"], obj["interval"]];
var newObj = {
"x": arr.join(", "),
"y": timeData["count"],
}
if(newTimeData[obj["method"] + "Array"]) { // method found
newTimeData[obj["method"] + "Array"].push(newObj)
} else { // method not found
newTimeData[obj["method"] + "Array"] = [newObj]
}
}
// PRETTY PRINTING OBJECT
console.log(JSON.stringify(newTimeData, undefined, 4))
/*...
{
"200Array": [
{
"x": "2018, 6, 11, 12, 45",
"y": 1
},
{
"x": "2016, 11, 11, 17, 10",
"y": 47
}
],
"404Array": [
{
"x": "2016, 11, 11, 16, 50",
"y": 5
}
]
}
...*/
// PRETTY PRINTING ARRAY POINTED BY '200Array' key
console.log(JSON.stringify(newTimeData["200Array"], undefined, 4))
/*...
[
{
"x": "2018, 6, 11, 12, 45",
"y": 1
},
{
"x": "2016, 11, 11, 17, 10",
"y": 47
}
]
...*/
// PRETTY PRINTING ARRAY POINTED BY '404Array' key
console.log(JSON.stringify(newTimeData["404Array"], undefined, 4))
/*...
[
{
"x": "2016, 11, 11, 16, 50",
"y": 5
}
]
...*/
Output ยป
H:\RishikeshAgrawani\Projects\Sof\FilterArrays>node FilterArrays.js
{
"200Array": [
{
"x": "2018, 6, 11, 12, 45",
"y": 1
},
{
"x": "2016, 11, 11, 17, 10",
"y": 47
}
],
"404Array": [
{
"x": "2016, 11, 11, 16, 50",
"y": 5
}
]
}
[
{
"x": "2018, 6, 11, 12, 45",
"y": 1
},
{
"x": "2016, 11, 11, 17, 10",
"y": 47
}
]
[
{
"x": "2016, 11, 11, 16, 50",
"y": 5
}
]

Using map to access nested json in react native

I am trying to access keys and arrays in my json structure with Array.map() but I'm missing something.
Here's my JSON:
{
"payload": [
{
"id": 1,
"name": "Atta",
"brands": [
{
"id": 118,
"name": "Wheatola",
"subProducts": [
{
"id": 858,
"name": "Chakki Aata",
"minPrice": 52,
"maxPrice": 56
},
{
"id": 2,
"name": "Chakki Atta",
"minPrice": 222,
"maxPrice": 236
}
]
}
]
},
{
"id": 16,
"name": "Rice (Branded)",
"brands": [
{
"id": 25,
"name": "CookStar",
"subProducts": [
{
"id": 1163,
"name": "Best Basmati",
"creditDays": 0,
"minPrice": 5600,
"maxPrice": 5600
},
{
"id": 863,
"name": "Extra Long Grain Basmati",
"creditDays": 0,
"minPrice": 7800,
"maxPrice": 7800
}
]
}
]
}
]
}
I want to access payload.name, payload.brands.name(s), payloads.brands.subproducts.name(s) with Array.map() and render the values in components. How do I access nested json like using map()?
Expected output is:
Atta, Wheatola, Chakki Aata
Atta, Wheatola, Chakki Aata
Rice (Branded), Cookstar, Best Basmati
Rice (Branded), Cookstar, Extra Long Grain Basmati
You need to nest Array.map()
var data = {
"payload": [
{
"id": 1,
"name": "Atta",
"brands": [
{
"id": 118,
"name": "Wheatola",
"subProducts": [
{
"id": 858,
"name": "Chakki Aata",
"minPrice": 52,
"maxPrice": 56
},
{
"id": 2,
"name": "Chakki Atta",
"minPrice": 222,
"maxPrice": 236
}
]
}
]
},
{
"id": 16,
"name": "Rice (Branded)",
"brands": [
{
"id": 25,
"name": "CookStar",
"subProducts": [
{
"id": 1163,
"name": "Best Basmati",
"creditDays": 0,
"minPrice": 5600,
"maxPrice": 5600
},
{
"id": 863,
"name": "Extra Long Grain Basmati",
"creditDays": 0,
"minPrice": 7800,
"maxPrice": 7800
}
]
}
]
}
]
}
const renderData = data.payload.map((payload) => {
return payload.brands.map(brand =>{
return brand.subProducts.map(subProduct => {
return `${payload.name}, ${brand.name}, ${subProduct.name}`
}).join("\n")
}).join("\n")
}).join("\n")
console.log(renderData);
Here might be a working example (without styling or anything):
render() {
return (
<div>
{
json.payload.map(j =>
<div>
{j.name}
{j.brands.map(b =>
<div>
{b.name}
{b.subProducts.map(s =>
<div>
{s.name}
</div>)
}
</div>
)}
</div>
)
}
</div>
);
}
You probably need to style it, or combine it with a table and columns, because it just renders the values now.
You can also use forEach since you'll have to nest map calls but you expect a flat array (?) in the end :
var json = {
"payload": [{
"id": 1,
"name": "Atta",
"brands": [{
"id": 118,
"name": "Wheatola",
"subProducts": [{
"id": 858,
"name": "Chakki Aata",
"minPrice": 52,
"maxPrice": 56
},
{
"id": 2,
"name": "Chakki Atta",
"minPrice": 222,
"maxPrice": 236
}
]
}]
},
{
"id": 16,
"name": "Rice (Branded)",
"brands": [{
"id": 25,
"name": "CookStar",
"subProducts": [{
"id": 1163,
"name": "Best Basmati",
"creditDays": 0,
"minPrice": 5600,
"maxPrice": 5600
},
{
"id": 863,
"name": "Extra Long Grain Basmati",
"creditDays": 0,
"minPrice": 7800,
"maxPrice": 7800
}
]
}]
}
]
}
var result = [];
json.payload.forEach(product => {
product.brands.forEach(brand => {
brand.subProducts.forEach(subProduct => {
result.push([product.name, brand.name, subProduct.name].join(', '));
});
});
});
console.log(result);

How to sort by an associative array value(Complex array structure)?

Consider the Following:
I am representing data in an array in an HTML table such as:
1) How would I sort the array by b1 or b3?
I have tried:
var o = {
"orgs": {
"655": {
"data": {
"cons": 30,
"b3ports": 0,
"b9": 2,
"b1": 25,
"b2": 14,
"b3": 10,
"ports": 0,
"rica": 30
},
"depth": 1,
"agents": [207072],
"orgunit_id": "TEAM00655",
"name": "TEAM00655: Jabba - Mooi River (Muhammad Jaffar)"
},
"853": {
"data": {
"cons": 356,
"b3ports": 1,
"b9": 8,
"b1": 283,
"b2": 122,
"b3": 77,
"ports": 1,
"rica": 356
},
"depth": 2,
"agents": [208162],
"orgunit_id": "TEAM00853",
"name": "TEAM00853: Jabba - Mooiriver (Bongiwe Gwala)"
},
"921": {
"data": {
"cons": 22,
"b3ports": 0,
"b9": 2,
"b1": 20,
"b2": 7,
"b3": 5,
"ports": 0,
"rica": 22
},
"depth": 1,
"agents": [210171, 212842],
"orgunit_id": "TEAM00921",
"name": "TEAM00921: Jabba - Nolwazi Zungu"
},
},
"agents": {
"207072": {
"name": "Bongiwe Gwala",
"oid": 655,
"depth": 1,
"aid": "A0207072",
"orgunit_id": "TEAM00655",
"data": {
"cons": 30,
"b3ports": 0,
"b9": 2,
"b1": 25,
"b2": 14,
"b3": 10,
"ports": 0,
"rica": 30
},
"aname": "A0207072: Bongiwe Gwala",
"oname": "TEAM00655: Jabba - Mooi River (Muhammad Jaffar)"
},
"208162": {
"name": "Nkosikhona MADLALA",
"oid": 853,
"depth": 2,
"aid": "A0208162",
"orgunit_id": "TEAM00853",
"data": {
"cons": 356,
"b3ports": 1,
"b9": 8,
"b1": 283,
"b2": 122,
"b3": 77,
"ports": 1,
"rica": 356
},
"aname": "A0208162: Nkosikhona MADLALA",
"oname": "TEAM00853: Jabba - Mooiriver (Bongiwe Gwala)"
},
"212842": {
"name": "SANELE KHUMALO",
"oid": 921,
"depth": 1,
"aid": "A0212842",
"orgunit_id": "TEAM00921",
"data": {
"cons": 22,
"b3ports": 0,
"b9": 2,
"b1": 20,
"b2": 7,
"b3": 5,
"ports": 0,
"rica": 22
},
"aname": "A0212842: SANELE KHUMALO",
"oname": "TEAM00921: Jabba - Nolwazi Zungu"
},
},
"orglist": [853, 655, 921],
}
function sort_data(data, sortby, asc) {
console.log(data);
if (asc == "asc") {
data.sort(function(a, b) {
a.sortby - b.sortby;
});
} else {
data.sort(function(a, b) {
a.sortby + b.sortby;
});
}
// update_data;
}
var a = sort_data(o, "b1", "asc");
console.log(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This how ever gives me an error( To view the error, open your console )
UPDATE:
I got the sorting to work thanks to #NicolasAlbert.
Now I need to order by the agents aswell. It needs to order by orgs first and then by agents I have tried:
if (asc == "desc") {
data.orglist.sort(function(a, b) {
a_org = data.orgs[a].data[sortby];
b_org = data.orgs[b].data[sortby];
a_agent = data.agents[a].data[sortby];
b_agent = data.agents[b].data[sortby];
// return d - c;
return b_org - a_org && a_agent - b_agent;
// data.agents[a].data[sortby] - data.agents[b].data[sortby]
});
} else {
data.orglist.sort(function(a, b) {
a_org = data.orgs[a].data[sortby];
b_org = data.orgs[b].data[sortby];
a_agent = data.agents[a].data[sortby];
b_agent = data.agents[b].data[sortby];
return a_org - b_org && a_agent - b_agent;
});
}
This does not work how ever...
Another update
I have modified my code to do:
data.orglist.sort(function(a, b) {
a_org = data.orgs[a].data[sortby];
b_org = data.orgs[b].data[sortby];
agents = data.orgs[b].agents.sort(function(a, b){
a_agent = data.agents[a].data[sortby];
b_agent = data.agents[b].data[sortby];
return b_agent - a_agent
});
return b_org - a_org && agents;
});
But this sorts both orgs and agents at the same time.
LAst update:
I got it to work, sorting both the orgs and the agents, I had to create two sorting functions:
function sort_org(data, sortby, order) {
/*
Sort the orgs
*/
var a_org, b_org;
if (order == "desc") {
data.orglist.sort(function(a, b) {
a_org = data.orgs[a].data[sortby];
b_org = data.orgs[b].data[sortby];
return b_org - a_org;
});
} else {
data.orglist.sort(function(a, b) {
a_org = data.orgs[a].data[sortby];
b_org = data.orgs[b].data[sortby];
return a_org - b_org;
});
}
}
function sort_agent(data, sortby, order) {
/*
Sort the agents
*/
var a_agent, b_agent;
if (order == "desc") {
for (var orgid in data.orglist){
data.orgs[data.orglist[orgid]].agents.sort(function(a, b){
a_agent = data.agents[a].data[sortby];
b_agent = data.agents[b].data[sortby];
return b_agent - a_agent
})
}
} else {
for (var orgid in data.orglist){
data.orgs[data.orglist[orgid]].agents.sort(function(a, b){
a_agent = data.agents[a].data[sortby];
b_agent = data.agents[b].data[sortby];
return a_agent - b_agent
})
}
}
}
then I just call the functions consecutively... i.e.
sort_org(o, "b1", "asc");
sort_agent(o, "b1", "asc");
I hope this can help someone...
You can only use .sort method on Array instance, not Object. Your data is store in key/value objects and the order cannot be modified.
If you want order your data, you must introduce Array ([]) in it.
May you want order the orglist array like that:
var o = {
"orgs": {
"655": {
"data": {
"cons": 30,
"b3ports": 0,
"b9": 2,
"b1": 25,
"b2": 14,
"b3": 10,
"ports": 0,
"rica": 30
},
"depth": 1,
"agents": [207072],
"orgunit_id": "TEAM00655",
"name": "TEAM00655: Jabba - Mooi River (Muhammad Jaffar)"
},
"853": {
"data": {
"cons": 356,
"b3ports": 1,
"b9": 8,
"b1": 283,
"b2": 122,
"b3": 77,
"ports": 1,
"rica": 356
},
"depth": 2,
"agents": [208162],
"orgunit_id": "TEAM00853",
"name": "TEAM00853: Jabba - Mooiriver (Bongiwe Gwala)"
},
"921": {
"data": {
"cons": 22,
"b3ports": 0,
"b9": 2,
"b1": 20,
"b2": 7,
"b3": 5,
"ports": 0,
"rica": 22
},
"depth": 1,
"agents": [210171, 212842],
"orgunit_id": "TEAM00921",
"name": "TEAM00921: Jabba - Nolwazi Zungu"
},
},
"agents": {
"207072": {
"name": "Bongiwe Gwala",
"oid": 655,
"depth": 1,
"aid": "A0207072",
"orgunit_id": "TEAM00655",
"data": {
"cons": 30,
"b3ports": 0,
"b9": 2,
"b1": 25,
"b2": 14,
"b3": 10,
"ports": 0,
"rica": 30
},
"aname": "A0207072: Bongiwe Gwala",
"oname": "TEAM00655: Jabba - Mooi River (Muhammad Jaffar)"
},
"208162": {
"name": "Nkosikhona MADLALA",
"oid": 853,
"depth": 2,
"aid": "A0208162",
"orgunit_id": "TEAM00853",
"data": {
"cons": 356,
"b3ports": 1,
"b9": 8,
"b1": 283,
"b2": 122,
"b3": 77,
"ports": 1,
"rica": 356
},
"aname": "A0208162: Nkosikhona MADLALA",
"oname": "TEAM00853: Jabba - Mooiriver (Bongiwe Gwala)"
},
"212842": {
"name": "SANELE KHUMALO",
"oid": 921,
"depth": 1,
"aid": "A0212842",
"orgunit_id": "TEAM00921",
"data": {
"cons": 22,
"b3ports": 0,
"b9": 2,
"b1": 20,
"b2": 7,
"b3": 5,
"ports": 0,
"rica": 22
},
"aname": "A0212842: SANELE KHUMALO",
"oname": "TEAM00921: Jabba - Nolwazi Zungu"
},
},
"orglist": [853, 655, 921]
}
function sort_data(data, sortby, asc) {
console.log(data);
if (asc == "asc") {
data.orglist.sort(function(a, b) {
data.orgs[a].data[sortby] - data.orgs[b].data[sortby];
});
} else {
data.orglist.sort(function(a, b) {
data.orgs[b].data[sortby] - data.orgs[a].data[sortby];
});
}
// update_data;
}
sort_data(o, "b1", "asc");
console.log(o.orglist);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories

Resources