Loop JSON and stop when condition met. Then count the objects - javascript

I have a json file with a list of users and points. I want to somehow Loop through until the _id == userId, then count how many objects there are to get their position.
So far I have this json file which has the points in desc order already
[
{
"_id":"55db8684ce3bf55b4b612a72",
"firstname":"Billy",
"lastname":"Bob",
"points":3109373
},
{
"_id":"55dbdffeaba8ee274d3b9f89",
"firstname":"Steve",
"lastname":"Jones",
"points":34434
},
{
"_id":"55dbdbf756b0fa064dd3e507",
"firstname":"Jim",
"lastname":"Kirk",
"points":1000
},
{
"_id":"55dbdc2756b0fa064dd3e508",
"firstname":"Casey",
"lastname":"Jones",
"points":36
},
{
"_id":"55dbdbd656b0fa064dd3e506",
"firstname":"Reg",
"lastname":"Barclay",
"points":33
},
]
What I need to do is find the position for the user using their ID. So far I have but the position always returns undefined.
$.each(obj, function(index, value) {
var returnObj = (this === "<%= user._id %>");
var position = returnObj.length;
console.log('user position is ' + position);
});
But this always returns undefined 11 times, which is what the position should be.

If I got you right, using for instead of each works which is much faster and not much to code.
try this,
for(var i =0;i < obj.length; i++)
{
if(obj[i]['_id'] == "55dbdc2756b0fa064dd3e508"){
alert('position :' + parseInt(i + 1)); //<--position in an obj
alert('index :' + i); //<----actual index
break;
}
}
var obj=[
{
"_id":"55db8684ce3bf55b4b612a72",
"firstname":"Billy",
"lastname":"Bob",
"points":3109373
},
{
"_id":"55dbdffeaba8ee274d3b9f89",
"firstname":"Steve",
"lastname":"Jones",
"points":34434
},
{
"_id":"55dbdbf756b0fa064dd3e507",
"firstname":"Jim",
"lastname":"Kirk",
"points":1000
},
{
"_id":"55dbdc2756b0fa064dd3e508",
"firstname":"Casey",
"lastname":"Jones",
"points":36
},
{
"_id":"55dbdbd656b0fa064dd3e506",
"firstname":"Reg",
"lastname":"Barclay",
"points":33
},
]
for(var i =0;i < obj.length; i++)
{
if(obj[i]['_id'] == "55dbdc2756b0fa064dd3e508"){
alert('position :' + parseInt(i + 1));
alert('index :' + i);
break;
}
}

Related

loop object form saved search netsuite

I have created a saved search and filtering report for header and child record and i have pushed
var parseDataObj = {};
if (!parseDataObj[internalid]) {
parseDataObj[internalid] = {
account: account,
taxtotal: taxtotal,
subtotal: subtotal,
nameVendor: nameVendor,
amontNew: amontNew,
internalid: internalid,
data_irp: [
{
item: item,
kemasanItem: kemasanItem,
cartonIRBar: cartonIRBar,
diskon1Ir: diskon1Ir,
bonusCarton: bonusCarton,
bonusPcs: bonusPcs,
docNumIr: docNumIr,
},
],
};
} else {
parseDataObj[internalid].data_irp.push({
item: item,
kemasanItem: kemasanItem,
cartonIRBar: cartonIRBar,
diskon1Ir: diskon1Ir,
bonusCarton: bonusCarton,
bonusPcs: bonusPcs,
docNumIr: docNumIr,
});
}
var parseDataArr = [];
if (Object.keys(parseDataObj).length > 0) {
Object.keys(parseDataObj).map(function (key, index) {
parseDataArr.push(parseDataObj[key]);
});
}
log.debug("parse data ARR", parseDataArr);
and i have log.debug and data match to what i want. when i get record from taxtotal and it worked, but when i get data in the data_irp have error
if (parseDataArr.length > 0) {
for (var j = 0; j < parseDataArr.length; j++) {
xmlString +=
"<Row>" +
'<Cell ss:StyleID="MyAlign" ss:MergeAcross="0"><Data ss:Type="String"> ' +
parseDataArr[j].taxtotal +
"</Data></Cell>" +
"</Row>"; //its worked
if (parseDataArr.data_irp.length > 0) {
for (var k = 0; k < parseDataArr.data_irp.length; k++) {
// length undef (?)
xmlString +=
"<Row>" +
'<Cell ss:StyleID="MyAlign" ss:MergeAcross="0"><Data ss:Type="String"> </Data></Cell>' +
'<Cell ss:StyleID="MyAlign" ss:MergeAcross="3"><Data ss:Type="String"> ' +
parseDataArr.data_irp[k].item +
"</Data></Cell>" + //got error
"</Row>";
}
}
}
}
would you please help me for this error. thanks

Get values from JSON file and sort by key number value

I was wondering if someone could help me get this to work so it prints out values and sorts them by propertyCount, highest to lowest. Below gets me the the first 6 values from a JSON file.
Basically, Im trying to only grab 6 values from a JSON file where it's sorted by a key called count that has a number value. Any help is greatly appreciated.
var countyInfo = [];
var count = 0;
var propertyCount = 0;
function getCountyInfo($j) {
//$j.ajax({
// url: "/info.json?st=WA"
//}).done(function(data) {
//countyInfo = data;
countyInfo = getDataDemo();
$j.each(countyInfo.counts.county_info, function(key, value) {
$j.each(value, function(key, value) {
if (key == "count") {
propertyCount = value;
}
if (key == "countyName" && value != null) {
var countyName = value;
if (count < 6) {
$j('#countyList').append('<li class="topCountyRow">' + countyName + ' (' + propertyCount + ')</li>');
}
count++;
}
});
});
//});
}
(function($j) {
//loaded();
var county_info = [];
getCountyInfo($j);
})(jQuery);
// Just for the StackOverflow Question
function getDataDemo() {
return JSON.parse(`{
"state": "wa",
"stateName": "Washington",
"counts": {
"county_info": [
{
"count": 72,
"countyName": "Anderson"
},
{
"count": 43,
"countyName": "Angelina"
}
]
}
}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="countyList" class="ulTwoColumns"></ul>
You can use sort function of array where you need to pass comparer function as below.
function sort(data)
{
return data.counts.county_info.sort((left,right)=>{
return left.count<right.count?1:-1;
})
}
Updated as per your data.
Use the sort method to compare and sort
data.counts.county_info.sort(a, b => a.count < b.count);
Implementing in your code above
function getCountyInfo(){
$j.ajax({
url: "/info.json?st=WA"
}).done(function(data) {
let sortedData = data.counts.county_info.sort(a, b => a.count < b.count);
// other things to do
});
}

Java script for loop Parse Promise

I am trying to read a file on parse.com and using a for loop iterate over all the records present in it. On each record, I need to perform 4 operations, each dependent on the other. Can someone please guide how I can do that so that each record is processed in the for loop.
Parse.Cloud.httpRequest({
url: urlValue
}).then(function(fileResponse) {
console.log("processUploadFile:httpRequest:response:" + JSON.stringify(fileResponse.buffer.length));
// console.log("processUploadFile:Text:" + fileResponse.text);
var records = fileResponse.text.split("\r");
for (var i = 0; i < records.length; ++i) {
// console.log("Record:" + i + " detail:" + records[i] + "\n\n");
var record = records[i];
console.log("processUploadFile:adding patient");
Parse.Cloud.run("addPatient", {
record:record
}, {
success: function(objectId) {
console.log("Created objectId:" + JSON.stringify(objectId));
Parse.Cloud.run("addProvider", {
record:record
}, {
success: function(objectId) {
console.log("Created objectId:" + JSON.stringify(objectId));
Parse.Cloud.run("addLocation", {
record:record
}, {
success: function(objectId) {
console.log("objectId:" + JSON.stringify(objectId));
},
error: function(error) {
console.log(JSON.stringify(error));
}
});
},
error: function(error) {
console.log(JSON.stringify(error));
}
});
},
error: function(error) {
console.log(JSON.stringify(error));
}
});
};
}
}
response.success();
});
The right right answer depends on the semantics of those operations, whether they depend on each other in any way. The other part of a right right answer accounts for transaction rate limits and timeouts imposed by parse.com. That also depends on what happens in the cloud operations and how much data is being processed.
But the right answer (as opposed to right right) is to perform operations serially by chaining promises' then(), and to perform groups of operations concurrently (or in arbitrary order) with Parse.Promise.when().
One such ordering would look like this:
var patientQs = [];
var providerQs = [];
var locationQs = [];
var records;
Parse.Cloud.httpRequest({url: urlValue}).then(function(fileResponse) {
console.log("processUploadFile:httpRequest:response:" + JSON.stringify(fileResponse.buffer.length));
records = fileResponse.text.split("\r");
for (var i = 0; i < records.length; ++i) {
// console.log("Record:" + i + " detail:" + records[i] + "\n\n");
var record = records[i];
patientQs.push(Parse.Cloud.run("addPatient", {record:record}));
providerQs.push(Parse.Cloud.run("addProvider", {record:record}));
locationQs.push(Parse.Cloud.run("addLocation", {record:record}));
}
return Parse.Promise.when(patientQs);
}).then(function() {
// since the result of addPatient is an objectId, arguments
// will be the corresponding objectIds for each run
for (var i=0; i<arguments.length; i++) {
console.log(arguments[i] + " is the object id for input record " + JSON.stringify(records[i]));
}
return Parse.Promise.when(providerQs);
}).then(function() {
return Parse.Promise.when(locationQs);
}).then(function() {
response.success();
}, function(error) {
response.error(error);
});
This says, "go thru the http-retrieved records, and first add all of the patients for those records, then add all of the providers, and so on".
Or, you could group the operations by input record, like this:
Parse.Cloud.httpRequest({url: urlValue}).then(function(fileResponse) {
console.log("processUploadFile:httpRequest:response:" + JSON.stringify(fileResponse.buffer.length));
var records = fileResponse.text.split("\r");
var recordQs = [];
for (var i = 0; i < records.length; ++i) {
// console.log("Record:" + i + " detail:" + records[i] + "\n\n");
var record = records[i];
recordQs.push(processARecord(record));
}
return Parse.Promise.when(recordQs);
}).then(function() {
response.success(arguments);
}, function(error) {
response.error(error);
});
function processARecord(record) {
var result = {};
return Parse.Cloud.run("addPatient", {record:record}).then(function(objectId) {
console.log(objectId + " is the object id for input record " + JSON.stringify(record));
result.patientId = objectId;
return Parse.Cloud.run("addProvider", {record:record});
}).then(function (providerId) {
result.providerId = providerId;
return Parse.Cloud.run("addLocation", {record:record});
}).then(function(locationId) {
result.locationId = locationId;
return result;
});
}

jquery dynamic content and date output

var jsonObj = jQuery.parseJSON(passData);
thisId = jsonObj.id;
thisPage = jsonObj.page;
thisPageItem = jsonObj.item;
if (jsonObj.json != undefined) {
$.each(jsonObj.json, function (key, tempJson) {
if (tempJson.position != undefined) {
var tempId = tempJson.id;
var tempStyle = tempJson.position;
objJsonArr[tempId] = tempStyle;
}
});
}
for (var i = 1; i < 9; i++) {
var tempList = window.objJsonArr;
var tempDom = '#dropAbleArea #area.' + i;
$(tempDom).css('top', dropObjectPositionArr[i].top);
$(tempDom).css('left', dropObjectPositionArr[i].left);
console.log("Out " + objJsonArr[i]);
$(tempDom).load('images/pageThree/' + i + '.svg', null, function (e) {
console.log("In " + objJsonArr[i]);
});
}
$.each(objJsonArr, function (key, value) {
if (value != undefined) {
$('#dropAbleArea div#area').on('', function (e) {
$('#dropAbleArea div#area.' + key + ' g#ball path#bk').attr('style', value);
});
};
});
the return is
[Log] Out fill:rgb(244, 133, 142) (3.html, line 130)
[Log] Out fill:rgb(130, 202, 156) (3.html, line 130)
[Log] Out fill:rgb(207, 229, 174) (3.html, line 130)
[Log] Out fill:rgb(130, 202, 156) (3.html, line 130)
[Log] Out undefined (3.html, line 130, x4)
[Log] In undefined (3.html, line 132, x8)
Q1: I can't get the javascript array data in the console.log("In " + objJsonArr[i]);
Q2: How can i get the dynamic content in the
$('#dropAbleArea div#area').on('',function(e){
$('#dropAbleArea div#area.' + key +' g#ball path#bk').attr('style',value);
});
The complete function given to jQuery .load captures the variables objJsonArr and i. But when the function is executed, the loop has already finished and i has the value 9 and objJsonArr[9] seems to be undefined.
You can see the same effect with a delayed function
var a = [ 1, 2, 3 ];
for (var i = 0; i < a.length; ++i) {
setTimeout(function() {
console.log('a[' + i + ']=' + a[i]);
}, 500);
}
which gives the output
a[3]=undefined
JSFiddle
You can "fix" this with creating an additional scope by wrapping the anonymous function, where you capture the loop variable's value in a another variable k
var a = [ 1, 2, 3 ];
for (var i = 0; i < a.length; ++i) {
setTimeout((function(k, v) {
return function() {
console.log('a[' + k + ']=' + v);
};
})(i, a[i]), 500);
}
JSFiddle
In your case, this would be something like
$(tempDom).load('images/pageThree/' + i + '.svg', null, (function(v) {
return function (e) {
console.log("In " + v);
};
})(objJsonArr[i]));
Update:
I just learned about jQuery.proxy() and it seems to be the solution to your problem. Taking my first example and applying jQuery.proxy to it will give
var a = [ 1, 2, 3 ];
for (var i = 0; i < a.length; ++i) {
setTimeout($.proxy(function(k, v) {
console.log('a[' + k + ']=' + v);
}, null, i, a[i]), 500);
}
JSFiddle
This is equivalent to the closure in my second example, where the two values are captured. Equally, using $.proxy in your program will be
$(tempDom).load('images/pageThree/' + i + '.svg', null, $.proxy(function (v, e) {
console.log("In " + v);
}, null, objJsonArr[i]));

Recursively Search in JSON or Javascript Object

For example:
[{
id:'our-purpose',
title:'Our Purpose',
slug:'/our-purpose',
backgroundImage:'images/bg-our-purpose.jpg',
showInNav:1
},
{
id:'our-people',
title:'Our People',
slug:'/our-people',
backgroundImage:'images/bg-our-people.jpg',
showInNav:1,
subpages:[
{
id:'attorneys',
title:'Attorneys',
slug:'/our-people/attorneys',
subpages:[
{
id:'attorneys-cdb',
title:'Attorneys - Carla DeLoach Bryant',
slug:'/our-people/attorneys/carla'
},
{
id:'attorneys-jad',
title:'Attorneys - Jordan A. DeLoach',
slug:'/our-people/attorneys/jordan'
},
{
id:'attorneys-shh',
title:'Attorneys - Sarah H. Hayford',
slug:'/our-people/attorneys/sarah'
},
{
id:'attorneys-jsp',
title:'Attorneys - Jason S. Palmisano',
slug:'/our-people/attorneys/jason'
},
{
id:'attorneys-ldw',
title:'Attorneys - Lindsey DeLoach Wagner',
slug:'/our-people/attorneys/carla'
},
]
},
{
id:'legal-support',
title:'Legal Support',
slug:'/our-people/legal-support',
subpages:[
{
id:'legal-support-tb',
title:'Legal Support - Theolyn Brock',
slug:'/our-people/attorneys/theolyn'
},
{
id:'legal-support-cd',
title:'Legal Support - Cheri DeFries',
slug:'/our-people/attorneys/cheri'
},
]
},
//...and so on
You'll notice that you could do json[1].subpages[0].subpages[0] but I don't know how deep it's going to be. This is written by a designer client of mine for an AJAX site he's building for a client. I'm trying to generate a navigation amongst other things and need to be able to:
A. Parse this recursively to build a navigation (<ul><li><a>...)
B. Search for a matching id. Like this (but this isn't recursive)[and ignore the for...in, its just for example's sake)
var matchId(id,json){
for(x in json){
if(json[x].id == id){ var theMatch = json[x]; break; }
}
}
This code builds the nav for you:
function buildNavForNode(node) {
var result = "<li id='" + node.id + "'><a href='" + node.slug + "'>" + node.title + "</a>";
if(node.subpages == undefined) {
return result + "</li>";
} else {
return result + buildNavForNodes(node.subpages) + "</li>";
}
}
function buildNavForNodes(nodes) {
var result = "<ul>";
var i = 0;
var len = nodes.length;
for(; i < len; i++) {
result += buildNavForNode(nodes[i]);
}
return result + "</ul>";
}
Here's how you'd use it:
var testData = [
{
id:'our-purpose',
title:'Our Purpose',
slug:'/our-purpose',
backgroundImage:'images/bg-our-purpose.jpg',
showInNav:1
},
{
id:'our-people',
title:'Our People',
slug:'/our-people',
backgroundImage:'images/bg-our-people.jpg',
showInNav:1,
subpages:[
{
id:'attorneys',
title:'Attorneys',
slug:'/our-people/attorneys',
subpages:[
{
id:'attorneys-cdb',
title:'Attorneys - Carla DeLoach Bryant',
slug:'/our-people/attorneys/carla'
},
{
id:'attorneys-jad',
title:'Attorneys - Jordan A. DeLoach',
slug:'/our-people/attorneys/jordan'
},
{
id:'attorneys-shh',
title:'Attorneys - Sarah H. Hayford',
slug:'/our-people/attorneys/sarah'
},
{
id:'attorneys-jsp',
title:'Attorneys - Jason S. Palmisano',
slug:'/our-people/attorneys/jason'
},
{
id:'attorneys-ldw',
title:'Attorneys - Lindsey DeLoach Wagner',
slug:'/our-people/attorneys/carla'
},
]
},
{
id:'legal-support',
title:'Legal Support',
slug:'/our-people/legal-support',
subpages:[
{
id:'legal-support-tb',
title:'Legal Support - Theolyn Brock',
slug:'/our-people/attorneys/theolyn'
},
{
id:'legal-support-cd',
title:'Legal Support - Cheri DeFries',
slug:'/our-people/attorneys/cheri'
},
]
}
]
}
];
$(function(){
htmlToInsert = buildNavForNodes(testData);
console.log(htmlToInsert);
$('body').html(htmlToInsert);
});
You can do this quite readily with a recursive function, but I think this nicely delineates the separation of duties between figuring out what to do with a collection of pages and processing a single page itself.
Here's a start (in some mix of JavaScript and pseudocode):
function createMenu(data) {
create UL
for each item in data {
create LI for item in UL
if the item has subpages {
append createMenu(item.subpages) to the LI
}
}
return UL
}
function findByID(data, id) {
for each item in data {
if(item.id==id) {
return the item
}
if item has subpages {
if findByID(item.subpages, id) is not null, return the result
}
}
return null;
}
function matchId(id, json){
if (!(json && "object" === typeof json)) { return; }
if (json.id === id) { return json; }
for (var x in json){
if (Object.hasOwnProperty.call(json, x)) {
var result = matchId(id, json[x]);
if (result !== undefined) { return result; }
}
}
}
I would give a try for JSONPath you can find the code here.
I generated the nav with this code since I only wanted the first level:
$('#sidebar').append('<ul></ul>');
for(x in PAGES){
if(PAGES[x].showInNav == 1){
$('#sidebar > ul').append('<li data-id="'+PAGES[x].id+'">'+PAGES[x].title+'</li>');
if(PAGES[x].subpages){
$('#sidebar > ul > li:last').append('<ul></ul>');
for(y in PAGES[x].subpages){
$('#sidebar > ul > li:last > ul').append('<li data-id="'+PAGES[x].subpages[y].id+'">'+PAGES[x].subpages[y].title+'</li>');
}
}
}
}
Then, for the recursive match function I ended up with this code:
var matchKey = function(k,v,j){
k = k || 'id'; //key
v = v || ''; //value
j = j || PAGES; //json
for(x in j){
if(j[x][k] == v){
return j[x];
}
if(j[x].subpages){
var result = matchKey(k,v,j[x].subpages);
if(result !== undefined){
return result;
}
}
}
}

Categories

Resources