parsing Objects in a loop in javascript - javascript

I have a string which I get from an api call and then I parse it into an object using JSON.parse(meetResponse)
meetResponse = {
"returncode":"SUCCESS",
"meetingName":"bbb meeting",
"meetingID":"712",
"createTime":"1457969919738",
"createDate":"Mon Mar 14 11:38:39 EDT 2016",
"voiceBridge":"35014",
"dialNumber":"613-555-1234",
"attendeePW":"PDmAJD4n",
"moderatorPW":"mpassword",
"running":"true",
"duration":"0",
"hasUserJoined":"true",
"recording":"true",
"hasBeenForciblyEnded":"false",
"startTime":"1457969919743",
"endTime":"0","participantCount":"2",
"maxUsers":"20",
"moderatorCount":"2",
"attendees":{
"attendee":[
{
"userID":"10005655",
"fullName":"Snedden Gonsalves",
"role":"MODERATOR",
"customdata":{}
},{
"userID":"10005656",
"fullName":"SneddenReg Gonsalves",
"role":"MODERATOR",
"customdata":{}
}
]
},
"metadata":{},
"messageKey":{},
"message":{}
}
I want to parse 'attendee' under 'attendees' to see who is present
The logic I use right now is :
//check if current user is already present in the meeting
for (var key in meetInfo.attendees.attendee){
console.log('key:',meetInfo.attendees.attendee[key]);
console.log(meetInfo.attendees.attendee[key].userID+"==="+user_id);
if(meetInfo.attendees.attendee[key].userID===user_id){
console.log('in meeting..');
inMeeting=true;
break;
}
else{
inMeeting=false;
}
}
Note:meetInfo is the Whole object
This works is there are more than one attendee but for one attendee it fails.
I am looking for something which would work for any number of 'attendees'.
Also I tried meetInfo.attendees.length instead of Object.keys(meetInfo.attendees).length but it didn't like it

It sounds like your attendees.attendee property could be either an array if multiple, or an object if singular. When it is an array your key variable in the for..in block will be populated the index. When it is an object, it will be populated with the property key.
Two things. First, you can make sure you are always working with an array by concatenating the value with an empty array:
var attendeeList = [].concat(meetInfo.attendees.attendee);
Second, you should not use for..in for iterate through an array. Use a classic for loop instead:
for (var idx= 0; idx < attendeeList.length; idx++)
console.log('key:',attendeeList[idx]);
console.log(attendeeList[idx].userID+"==="+user_id);
if(attendeeList[idx].userID===user_id){
console.log('in meeting..');
inMeeting=true;
break;
} else{
inMeeting=false;
}
}
Bonus, this loop is setting a variable true if any of the items in the array match. There is a special Array function for this:
inMeeting = [].concat(meetInfo.attendees.attendee)
.some(function(a){
return a.userID === user_id;
});

Related

Looping through nesting of objects and arrays with Javascript and underscore

I am trying to access objects that are nested within an array. I start with this JSON object (which was derived from an XML database output):
{"report":
{"date":"15 Apr 2016",
"metrics":
{"metric":
[
{"name":"Bank Angle",
"display_parent_group":"Bankfull",
"display_child_group":"SiteShape",
"tolerance":"0.05",
"visits":
{"visit":
[
{"visit_id":"3047","value": "0.47"},
{"visit_id":"2164","value": "0.55"},
{"visit_id":"1568","value": "0.72"},
{"visit_id":"3431","value": "0.12"},
{"visit_id":"2428","value": "0.44"},
{"visit_id":"1567","value": "0.49"}
]}},
{"name":"Bank Angle SD",
"display_parent_group":"Bankfull",
"display_child_group":"SiteShape",
"tolerance":"0.05",
"visits":
{"visit":
[
{"visit_id":"3047","value": "0.12"},
{"visit_id":"2164","value": "0.05"},
{"visit_id":"1568","value": "0.21"},
{"visit_id":"3431","value": "0.68"},
{"visit_id":"2428","value": "0.22"},
{"visit_id":"1567","value": "0.13"}
]}},
{"name":"Bankfull Area",
"display_parent_group":"Bankfull",
"display_child_group":"SiteSize","tolerance":"0.05",
"visits":
{"visit":
[
{"visit_id":"3047","value": "202"},
{"visit_id":"2164","value": "193"},
{"visit_id":"1568","value": "115"},
{"visit_id":"3431","value": "258"},
{"visit_id":"2428","value": "89"},
{"visit_id":"1567","value": "206"}
]}}
]
}
}
}
I then use underscore to extract a subset of metric objects:
var table_metric = JSONData.report.metrics.metric;
var target_metrics = _.where(table_metric, {
display_parent_group : 'Bankfull', display_child_group: 'SiteShape'
});
This results in an array with two nested objects. Where I'm having a problem is then accessing the array of objects which is nested inside visits.visit. If, for instance, I want to build an array of values associated with the key visit_id, and I try:
function buildVisitIDArray(target_metrics) {
var attrList = [];
for(var i=0; i<target_metrics.length; i++) {
var visit_records = target_metrics[i].visits[1];
console.log(visit_records);
for(visit_record in visit_records) {
attrList.push(_.pluck(visit_record, "visit_id"));
}
}
return attrList
}
I just get an array of undefined results. I've spent hours trying variations on the syntax to get at the nested "visit" objects, but I just can't seem to figure it out.
Any help is much appreciated for this novice!
In your buildVisitIDArray function, you are trying to get target_metrics[i].visits[1] as if it was an array, but it's actually an object, so you should use it this way:
function buildVisitIDArray(target_metrics) {
attrList = [];
for(var i=0; i<target_metrics.length; i++) {
var visit_records = target_metrics[i].visits; // Removed the array call ([1])
console.log(visit_records);
for(visit_record in visit_records) {
attrList.push(_.pluck(visit_records[visit_record], "visit_id"));
}
}
return attrList;
}
Hope it helps :)
You may also have an issue if you're not defining attrList with the var keyword somewhere else in your code.
Building on Andre's answer, you may want to change this line to be:
visit_records = target_metrics[i].visits.visit;
to go one layer deeper, then do a regular array for loop afterward.

how to update array of object in mongodb with for loop

i want to update nested mongo document with for loop here is my node.js code;
//loop starts
var update = {
"rate":mainRate,
"classifierCategories."+e+".rate":temiz[i].slice(0,2)
};
classifier.update({"classifierShortName":arrFile[1]},update,function(err){
console.log("updated - "+i+" - "+e);
});
//loop end
Error accurs ;
Unexpected token +
How can i update classifierCategories array with for loop
Your problem is how you are trying to notate the object "keys". This isn't valid for key construction in JavaScript object as the key names are literal and all characters are considered part of the name string.
Notate like this instead:
var update = { "rate": minRate };
update["classifierCategories."+e+".rate"] = temiz[i].slice(0,2);
That allows you to dynamically assign the key name like you want.

How can i navigate through the json?

I have some JSON which I have in a object but I can seem to return the values a sample of the json is as follows.
{
"rootLayout":"main",
"layoutDescriptions":[
{
"id":"main",
"container" : {
"type":"Tabs",
"content":[
{
"type":"Panel",
"label":"Simple Address",
"layout":"SimpleForm",
"comment":"This form is simple name value pairs",
"content":[
{ "type":"label", "constraint":"newline", "text":"Org Name" },
{ "type":"text", "property":"propOne" },
{ "type":"label", "constraint":"newline", "text":"Address" },
{ "type":"text", "property":"addrLine1" },
{ "type":"text", "property":"addrLine2" },
{ "type":"text", "property":"addrLine3" },
{ "type":"label", "constraint":"newline", "text":"Postcode" },
{ "type":"text", "property":"postcode" }
]
},
I am trying to return the rootLayout using
obj[0].rootLayout.id
This doesn't work also I am wondering how to access the content elements.
I am new to json and I have been thrown in the deep end I think. I cannot find any good reading on the internet can anyone recommend some.
Thanks.
Some explanation because you don't seem to understand JSON
It's not as complicated as one may think. It actually represents javascript objects as if they'd be written by code.
So if you have JSON written as:
{
id : 100,
name: "Yeah baby"
}
This means that your object has two properties: id and name. The first one is numeric and the second one is string.
In your example you can see that your object has two properties: rootLayout and layoutDescriptions. The first one jsonObj.rootLayout is string and will return "main" and the second one is an array:
layoutDescriptions: [ {...}, {...},... ]
Apparently an array of objects because array elements are enclosed in curly braces. This particular array element object that you provided in your example has its own properties just like I've explained for the top level object: id (string), container (another object because it's again enclosed in curlies) etc...
I hope you understand JSON notation a bit more.
So let's go to your question then
You can get to id by accessing it via:
jsonObj.layoutDescriptions[0].id
and further getting to your content objects:
var contentObjects = jsonObj.layoutDescriptions[0].container.content[0].content;
for(var i = 0; i < contentObjects.length, i++)
{
// assign this inner object to a variable for simpler property access
var contObj = contentObjects[i];
// do with this object whatever you need to and access properties as
// contObj.type
// contObj.property
// contObj.text
// contObj.constraint
}
Mind that this will only enumerate first content object's content objects... If this makes sense... Well look at your JSON object and you'll see that you have nested content array of objects.
The object is an object, not an array, and it doesn't have a property called 0.
To get rootLayout:
obj.rootLayout
However, rootLayout is a string, not an object. It doesn't have an id. The first item in the layoutDescriptions array does.
obj.layoutDescriptions[0].id
Are you trying to get one of layoutDescriptions with id equals to obj.rootLayout?
var targetLayout = {};
for(var i = 0; i < obj.layoutDescriptions.length; i++) {
if(obj.layoutDescriptions[i].id == obj.rootLayout) {
targetLayout = obj.layoutDescriptions[i]; break;
}
}
console.log(targetLayout);

How can I retrive a value from this json object?

<script>
var output = {"regions":{"4441":"Avtonomna Respublika Krym","4431":"Cherkas'ka Oblast'","4432":"Chernihivs'ka Oblast'","4433":"Chernivets'ka Oblast'","4434":"Dnipropetrovs'ka Oblast'","4435":"Donets'ka Oblast'","4436":"Ivano-Frankivs'ka Oblast'","4437":"Kharkivs'ka Oblast'","4438":"Khersons'ka Oblast'","4439":"Khmel'nyts'ka Oblast'","4440":"Kirovohrads'ka Oblast'","4443":"Kyyivs'ka Oblast'","4445":"L'vivs'ka Oblast'","4444":"Luhans'ka Oblast'","4442":"Misto Kyyiv","4450":"Misto Sevastopol","4446":"Mykolayivs'ka Oblast'","4447":"Odes'ka Oblast","4448":"Poltavs'ka Oblast'","4449":"Rivnens'ka Oblast'","4451":"Sums'ka Oblast'","4452":"Ternopil's'ka Oblast'","788":"Ukraine","4453":"Vinnyts'ka Oblast'","4454":"Volyns'ka Oblast'","4455":"Zakarpats'ka Oblast'","4456":"Zaporiz'ka Oblast'","4457":"Zhytomyrs'ka Oblast'"}}
alert(output.regions[1]);
</script>
This part gives me undefined:
alert(output.regions[1]);
How can I grab the first key/value pair for example. Basically I need to turn this into a select dropdown, the numeric keys would be the values and the names of the cities would be the option text.
Can iterate over it like:
for(key in output.regions) {
alert(key +' => '+output.regions[key]); // 4441 => Avtonomna Respublika Krym ...etc
}
Rather than a numeric index, you'll want to key into regions with the keys you've specified, like 4441, 4431, etc:
var output = {"regions":{"4441":"Avtonomna Respublika Krym","4431":"Cherkas'ka Oblast'","4432":"Chernihivs'ka Oblast'","4433":"Chernivets'ka Oblast'","4434":"Dnipropetrovs'ka Oblast'","4435":"Donets'ka Oblast'","4436":"Ivano-Frankivs'ka Oblast'","4437":"Kharkivs'ka Oblast'","4438":"Khersons'ka Oblast'","4439":"Khmel'nyts'ka Oblast'","4440":"Kirovohrads'ka Oblast'","4443":"Kyyivs'ka Oblast'","4445":"L'vivs'ka Oblast'","4444":"Luhans'ka Oblast'","4442":"Misto Kyyiv","4450":"Misto Sevastopol","4446":"Mykolayivs'ka Oblast'","4447":"Odes'ka Oblast","4448":"Poltavs'ka Oblast'","4449":"Rivnens'ka Oblast'","4451":"Sums'ka Oblast'","4452":"Ternopil's'ka Oblast'","788":"Ukraine","4453":"Vinnyts'ka Oblast'","4454":"Volyns'ka Oblast'","4455":"Zakarpats'ka Oblast'","4456":"Zaporiz'ka Oblast'","4457":"Zhytomyrs'ka Oblast'"}}
alert(output.regions[4441]); // alerts "Avtonomna Respublika Krym"
The regions entity is an object and not an array so you have to select its attribute by its associated key.
output.regions.4441
or
output.regions['4441']
The value with the key "regions" is a map, not an array - it has no ordering, therefore there is no concept of "first key/value pair" - you'll have to impose your own ordering if you want one.
This is because output.regions is an object, not an array. You would either need to access by the ID (778) or if you don't know it, than you can iterate to find it.
for (k in output.regions) { var key = k; break; }
alert(output.regions[key]);
There is no "first" value. Properties of javascript objects are not ordered. You can iterate over a javascript object like this:
for(key in output.regions){
alert(output.regions[key])
}
and check for the cycle of iteration, but there's no guarantee that the order won't change unexpectedly. To have a guaranteed order, you need to use an array.

How do i reverse JSON in JavaScript?

[
{"task":"test","created":"/Date(1291676980607)/"},
{"task":"One More Big Test","created":"/Date(1291677246057)/"},
{"task":"New Task","created":"/Date(1291747764564)/"}
]
I looked on here, and someone had the same sort of question, but the "checked" correct answer was that it will be different on IE if the item is deleted, which would be fine. My issue is, those items above are stored, but when i go and grab them, iterate, and return, the items are reversed and the created is at the 0 index and task is at 1. Also, i need to return this as JSON.
Here is my basic JS (value == an int the user is passing in):
outputJSON = {};
for(x in json[value]){
outputJSON[x] = _objectRevival(json[value][x]);
}
return outputJSON;
That returns:
created: Mon Dec 06 2010 15:09:40 GMT-0800 (Pacific Standard Time)
task: "test"
The order of the properties of an object is undefined. It is not possible to force them in a specified order. If you need them in a specific order, you can build this structure reliably using arrays:
var values = [
[["task", "test"], ["created", "/Date(1291676980607)/"]],
[["task", "One More Big Test"], ["created", "/Date(1291677246057)/"]],
[["task", "New Task"], ["created", "/Date(1291747764564)/"]]
];
Then you can iterate over your structure like this:
for (var i = 0; i < values.length; i++) {
for (var k = 0; k < values[i]; k++) {
// values[i][k][0] contains the label (index 0)
// values[i][k][1] contains the value (index 1)
}
}
To enforce a particular order for your output just replace json[value] in your for loop with an array of the object properties in the order you want to display them, in your case ["task", "created"].
The problem is that javascript objects don't store their properties in a specific order. Arrays on the other do (hence why you can get something consistent from json[0], json[1], json[2]).
If your objects will always have "task" and "created", then you can get at them in any order you want.
json[value]["task"]
and
json[value]["created"]
Update:
This should work with your existing code.
Before sending the json object:
var before = [
{"task":"test","created":"/Date(1291676980607)/"},
{"task":"One More Big Test","created":"/Date(1291677246057)/"},
{"task":"New Task","created":"/Date(1291747764564)/"}
];
var order = [];
for (var name in before[0]) {
order.push(name); // puts "task", then "created" into order (for this example)
}
Then send your json off to the server. Later when you get the data back from the server:
var outputJSON = {};
for (var x in order) {
if (order.hasOwnProperty(x)) {
outputJSON[order[x]] = _objectRevival(json[value][order[x]]); // I'm not sure what _objectRevival is...do you need it?
}
}
return outputJSON;
var items = ["bag", "book", "pen", "car"];
items.reverse();
This will result in the following output:
car , pen, book, bag
Even if you have JSON array it will reverse.

Categories

Resources