accessing a specific set of values from within my json response? - javascript

I am trying to use for..in loop to access the description key/value within 'Event' but at the moment am not fully sure how to achieve this. First of all I used the for..in and logged this out, this returns all the top level entries in the response, how do I now drill down and pick out Event.description? I first of all thought it was data[prop].Event.description but thats not the case. Should I be using a normal for loop and then the for..in inside of this?
Here is my current code:
$(document).ready(function() {
var data = {
"status": "ok",
"code": "200",
"message": "event details",
"data": [{
"Event": {
"id": "1",
"name": "Sample Event Number 1",
"description": "Sample Event Number 4 Description ....",
"event_date": "2012-05-31 00:00:00",
"Band": [{
"id": "1",
"name": "Support #1",
"BandsEvent": {
"id": "7",
"band_id": "2",
"event_id": "8",
"created": "2012-05-23 15:53:56",
"modified": "2012-05-23 15:53:56"
}},
{
"id": "2",
"name": "Support #2",
"BandsEvent": {
"id": "8",
"band_id": "1",
"event_id": "8",
"created": "2012-05-23 15:53:57",
"modified": "2012-05-23 15:53:57"
}}]
}},
{
"Event": {
"id": "2",
"name": "Sample Event Number 2",
"description": "Sample Event Number 4 Description ....",
"event_date": "2012-05-31 00:00:00",
"Band": [{
"id": "2",
"name": "Another Crazy Band",
"BandsEvent": {
"id": "3",
"band_id": "2",
"event_id": "8",
"created": "2012-05-23 15:53:56",
"modified": "2012-05-23 15:53:56"
}},
{
"id": "4",
"name": "The Band",
"BandsEvent": {
"id": "8",
"band_id": "1",
"event_id": "8",
"created": "2012-05-23 15:53:57",
"modified": "2012-05-23 15:53:57"
}}]
}}]
}
var prop;
for (prop in data) {
console.log( data[prop] );
// data.Event.description
}
});​

This should do what you want:
for (var i = 0; i < data.data.length; i++) {
console.log(data.data[i].Event.description);
}
I should add that the reason that your code doesn't work is that the "prop" variable would first be "status", then "code", then "message" and THEN "data". Status/code/message has no "Event" property, so therefore your code would return undefined if you'd try to access data[prop].Event. Here we pick them out specifically. And since that data.data is an array, there's no reason to use a for .. in loop, but rather just a regular for loop.
Likewise, if you would want to print out the descriptions AND the bands, you could do the following:
for (var i = 0; i < data.data.length; i++) {
console.log(data.data[i].Event.description + " has the following bands:");
for (var j = 0; j < data.data[i].Event.Band.length; j++) {
console.log(data.data[i].Event.Band[j].name);
}
}

Related

How can I concatenate this type of JSON in javascript?

How can I concatenate this json to obtain it:
complements = ["XYZ 3, CDE TR, AAA 5", "", "NDP 3, DDD FR"] ?
Each address can contain a set of complements which must be concatenated and separated by a comma.
P.s: I'm using javascript.
P.s2: Complements can be null like in the second group in JSON.
[
{
"postalcode": "1234",
"street": "ABC",
"number": "1",
"complement": [
{
"type": "B",
"name": "XYZ",
"description": "3"
},
{
"type": "C",
"name": "CDE",
"description": "TR"
},
{
"type": "D",
"name": "AAA",
"description": "5"
}
]
},
{
"postalcode": "444",
"street": "No complements",
"number": "5"
},
{
"postalcode": "2222",
"street": "BBB",
"number": "2",
"complement": [
{
"type": "E",
"name": "NDP",
"description": "3"
},
{
"type": "F",
"name": "DDD",
"description": "FR"
}
]
}
];
My code I'm getting this.complementsList.forEach is not a function.
getComplement(addressesResponse){
this.complementsList = JSON.parse(addressesResponse);
this.complementsList.forEach((item) => {
Object.defineProperty(item, 'complements', {
get: function() {
return this.complement.map((c) => `${c.name} ${c.description}`).join(', '); }
})
});
Source: https://salesforce.stackexchange.com/questions/367713/how-to-render-a-json-in-the-same-line-lwc
how i solved it :
arr.map((x)=>x.complement != null? (x.complement.map((y)=>y.name+' '+y.description)+"") :'');
Having a javascript object, you can go through the keys of the object and combine some of them into strings
It will look something like this:
const jsonObject = [{...}, {...}, ...]
const complements = [];
jsonObject.forEach((item) => {
let complement = item['complement'].reduce((result, currObj)
=> result += (currObj.name+' '+currObj.description), "");
complements.push(complement);
});
This is just an example. There are many ways to do it.

Trying to pick data from a JSON response text

I'm trying to pick some data from my JSON response text which looks like this:
{
"status": "success",
"reservations": [
{
"id": "22959",
"subject": "SubjectName",
"modifiedDate": "2017-04-03T06:04:24",
"startDate": "2017-04-03T12:15:00",
"endDate": "2017-04-03T17:00:00",
"resources": [
{
"id": "17",
"type": "room",
"code": "codeName",
"parent": {
"id": "2",
"type": "building",
"code": "buildingName",
"name": ""
},
"name": ""
},
{
"id": "2658",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "2446",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "3137",
"type": "realization",
"code": "codeName",
"name": ""
},
{
"id": "3211",
"type": "realization",
"code": "codeName",
"name": "name"
}
],
"description": ""
},
{
"id": "22960",
"subject": "subjectName",
"modifiedDate": "2017-04-04T06:04:33",
"startDate": "2017-04-04T10:00:00",
"endDate": "2017-04-04T16:00:00",
"resources": [
{
"id": "17",
"type": "room",
"code": "codeName",
"parent": {
"id": "2",
"type": "building",
"code": "codeName",
"name": ""
},
"name": ""
},
{
"id": "2658",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "2446",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
}
],
"description": ""
}
]
}
I've been trying to use JSON.parse() and go through the response text with a for-loop with no success. I need to pick the subject names, room names, building names and both student_group names.
This is what my code currently looks like:
var getData = {
"startDate":,
"endDate":,
"studentGroup": [
""]
};
var data = new XMLHttpRequest();
data.onreadystatechange = function () {
if (data.readyState == 4 && data.status == 200) {
try {
// Parse JSON
var json = JSON.parse(data.responseText);
// for-loops
for (var i = 0; i < json.reservations.length; i++) {
for (var x = 0; x < json.reservations[i].length;
x++) {
document.getElementById("test").innerHTML =
json.reservations[i].subject;
}
}
} catch (err) {
console.log(err.message);
return;
}
}
};
// JSON query
data.open("POST", "URL", true, "APIKEY", "PASS");
data.setRequestHeader('Content-Type', 'application/json');
data.send(JSON.stringify(getData));
This only prints the last subject name if I have more than 1 of them.
How should I do this?
Once you have your data parsed, forget it once was JSON. Now you have a JavaScript object.
Check data.status to make sure everything went well.
Loop over data.reservations and, inside that, over data.reservations[i].resources.
You should treat your parsed data as an object, so to get you going, this will get all unique student group names from all returned resources:
var studentGroups = [];
for (var i = 0; i < json.reservations.length; i++) {
if(json.reservations[i].resources != null){
for(var j = 0; j < json.reservations[i].resources.length; j++){
var resource = json.reservations[i].resources[j];
if(resource.type === "student_group"){
if(studentGroups.indexOf("groupName"))
studentGroups.push(resource.name);
}
}
}
}
}
Of course I'm not sure in what format you want to get your result (should this be a flat array or maybe another JSON, maybe only first value is important for you?), but I think you should already have an idea how to handle the topic.

Order of Array Elements Causing Error

I have two arrays. Elements of each array are shown as below:
allLabBranches = [{
"labbranchid": "1",
"labname": "Wahab Labs, Islampura Branch, Lahore",
"labtitle": "Wahab Labs Lahore",
"shortname": "WAHB",
"address": "56 Islampura, Lahore",
"landlineno": "04237940445",
"datecreated": "2016-03-11 11:00:00",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "2016-05-04 00:53:03",
"updatedbyname": "Jamshaid Sabir",
"updatedbyuserid": "1",
"clientgroups_clientgroupsid": "1",
"startdate": "2016-05-04"
}, {
"labbranchid": "2",
"labname": "Wahab Labs, Model Town Branch, Lahore",
"labtitle": "Wahab Labs Lahore",
"shortname": "WAHAB",
"address": "45 Model Town, Lahore",
"landlineno": "04237945485",
"datecreated": "2016-03-11 11:00:00",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "0000-00-00 00:00:00",
"updatedbyname": "",
"updatedbyuserid": "",
"clientgroups_clientgroupsid": "1",
"startdate": "0000-00-00"
}, {
"labbranchid": "3",
"labname": "Shahdara More Branch",
"labtitle": "Wahab Labs Lahore",
"shortname": "WAHAB",
"address": "Shahdara",
"landlineno": "04237933415",
"datecreated": "2016-03-11 11:48:15",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "0000-00-00 00:00:00",
"updatedbyname": "",
"updatedbyuserid": "",
"clientgroups_clientgroupsid": "1",
"startdate": "0000-00-00"
}, {
"labbranchid": "4",
"labname": "New Branch",
"labtitle": "Wahab Labs Lahore",
"shortname": "WAHB",
"address": "More Samanabad, Lahore",
"landlineno": "042361561",
"datecreated": "2016-03-11 11:52:06",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "2016-03-14 15:06:44",
"updatedbyname": "Jamshaid Sabir",
"updatedbyuserid": "1",
"clientgroups_clientgroupsid": "1",
"startdate": "2016-03-14"
}, {
"labbranchid": "5",
"labname": "Test Branch",
"labtitle": "xyz",
"shortname": "sfwe",
"address": "dsfasd",
"landlineno": "sdfasd",
"datecreated": "2016-03-12 00:14:11",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "2016-08-11 12:54:12",
"updatedbyname": "Jamshaid Sabir",
"updatedbyuserid": "1",
"clientgroups_clientgroupsid": "1",
"startdate": "2016-03-12"
}, {
"labbranchid": "6",
"labname": "Test Branch 2",
"labtitle": "asdfs",
"shortname": "asdfs",
"address": "asdf",
"landlineno": "asdf",
"datecreated": "2016-03-12 12:16:24",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "0000-00-00 00:00:00",
"updatedbyname": "",
"updatedbyuserid": "",
"clientgroups_clientgroupsid": "1",
"startdate": "2016-03-12"
}, {
"labbranchid": "7",
"labname": "Wahab Labs, Shahdara Branch, Lahore",
"labtitle": "Shahdara",
"shortname": "Shahdara",
"address": "Shahdara",
"landlineno": "0423744915",
"datecreated": "2016-08-11 12:56:27",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "2016-08-11 12:57:01",
"updatedbyname": "Jamshaid Sabir",
"updatedbyuserid": "1",
"clientgroups_clientgroupsid": "1",
"startdate": "2016-08-01"
}]
Another array elements are:
labsOfUser = [{
"userhasbranchid": "53",
"labbranches_labbranchid": "6",
"usersoflabs_userId": "9"
}, {
"userhasbranchid": "54",
"labbranches_labbranchid": "1",
"usersoflabs_userId": "9"
}, {
"userhasbranchid": "55",
"labbranches_labbranchid": "7",
"usersoflabs_userId": "9"
}, {
"userhasbranchid": "56",
"labbranches_labbranchid": "2",
"usersoflabs_userId": "9"
}]
Now I have a Select Multiple Box and I show some branches as selected and some as not selected. The code is given below:
function populateSelectedLabs() {
$('#labbranchids').empty();
if (allLabBranches.length >= labsOfUser.length) {
for (var i = 0; i < allLabBranches.length; i++) {
for (var j = 0; j < labsOfUser.length; j++) {
if (allLabBranches[i].labbranchid == labsOfUser[j].labbranches_labbranchid) {
$("#labbranchids").append("<option selected='selected' value='" + allLabBranches[i].labbranchid + "'>" + allLabBranches[i].labname + "</option>");
allLabBranches = jQuery.grep(allLabBranches, function(value) {
return value != allLabBranches[i];
});
} //end inner if
} //end inner loop
} //end outer loop
} //end if
for (var i = 0; i < allLabBranches.length; i++) {
$("#labbranchids").append("<option value='" + allLabBranches[i].labbranchid + "'>" + allLabBranches[i].labname + "</option>");
} //end for loop
} //end function
The problem is that array element comparison misses an element which is present in the array but located at different index in the array. The error occurs at following line of code:
if(allLabBranches[i].labbranchid == labsOfUser[j].labbranches_labbranchid){
Kindly help me to know how to compare all the elements in both array?
The reason why certain items are not matched is that you redefine the allLabBranches inside the loop on that same array, making it shorter.
Let's assume that before that change the following is true:
labsOfUser[j-1].labbranches_labbranchid == allLabBranches[i+1].labbranchid
You would expect this equality to be detected later, in the next iteration of the outer loop. But because of the re-assignment to allLabBranches, this value no longer is at index i+1, but at i. This value will no longer be matched during the remaining part of the inner loop (because the matching value is at j-1), and so i will increment for the next iteration of the outer loop. As a consequence this value will never be matched.
You could solve this by iterating backwards through the allLabBranches array, but even better would be to create a hash with the values from the labsOfUser array. This will have better performance.
You can do that like this:
function populateSelectedLabs() {
$('#labbranchids').empty();
// create hash
var hash = {};
for (var j = 0; j < labsOfUser.length; j++) {
hash[labsOfUser[j].labbranches_labbranchid] = 1;
}
allLabBranches = jQuery.grep(allLabBranches, function(value) {
return hash[value.labbranchid];
}).concat(jQuery.grep(allLabBranches, function(value) {
return !hash[value.labbranchid];
}));
for (var i = 0; i < allLabBranches.length; i++) {
$("#labbranchids").append($('<option>')
.val(allLabBranches[i].labbranchid)
.text(allLabBranches[i].labname)
.attr('selected', hash[allLabBranches[i].labbranchid]));
}
}
If the target browsers support ES6, then you could write it like this:
function populateSelectedLabs() {
$('#labbranchids').empty();
var hash = new Set(labsOfUser.map( value => value.labbranches_labbranchid ));
allLabBranches.filter( value => hash.has(value.labbranchid) )
.concat(allLabBranches.filter( value => !hash.has(value.labbranchid) ))
.forEach( value =>
$("#labbranchids").append($('<option>')
.val(value.labbranchid)
.text(value.labname)
.attr('selected', hash.has(value.labbranchid)))
);
}

Merging two json array object based on union and intersection

I am trying to merge two json array with objects as element. You may refer to this plunkr file for both json. I have succesfully retrieve the expected final outcome array id, but I do not know how to form back the expected json as below. I am using underscore js for this purpose.
Note: If object exist in newJson and not in currentJson, after merge, it will be inactive state by default.
I am not sure whether I am using the correct approach. This is what I have try:
var newJsonID = _.pluck(newJson, 'id');
var currentJsonID = _.pluck(currentJson, 'id');
var union = _.union(newJsonID, currentJsonID);
var intersection = _.intersection(currentJsonID, newJsonID);
var final = _.difference(union, _.difference( currentJsonID, intersection);
Expected Final Outcome:
[
{
"id": "12",
"property1Name": "1"
"status": "inactive"
},
{
"id": "11",
"property1Name": "1"
"status": "inactive"
},
{
"id": "10",
"property1Name": "1"
"status": "inactive"
},
{
"id": "9",
"property1Name": "1"
"status": "active"
}
]
A solution in plain Javascript with two loops and a hash table for lookup.
function update(newArray, currentArray) {
var hash = Object.create(null);
currentArray.forEach(function (a) {
hash[a.id] = a.status;
});
newArray.forEach(function (a) {
a.status = hash[a.id] || 'inactive';
});
}
var newJson = [{ "id": "12", "property1Name": "1" }, { "id": "11", "property1Name": "1" }, { "id": "10", "property1Name": "1" }, { "id": "9", "property1Name": "1" }],
currentJson = [{ "id": "10", "property1Name": "1", "status": "inactive" }, { "id": "9", "property1Name": "1", "status": "active" }, { "id": "8", "property1Name": "1", "status": "active" }, { "id": "7", "property1Name": "1", "status": "inactive" }];
update(newJson, currentJson);
document.write('<pre>' + JSON.stringify(newJson, 0, 4) + '</pre>');

Javascript | JSON and ARRAY

May be you can help me with my task. I have a JSON string:
{
"chats":[
{"id":"1","time":"13:02", "from_id":"2692","text":"1","to_id":"62"},
{"id":"2","time":"13:48", "from_id":"62","text":"Hello!","to_id":"2692"},
{"id":"12","time":"15:47", "from_id":"2692","text":"3","to_id":"62"},
{"id":"13","time":"15:48", "from_id":"62","text":"4","to_id":"2692"},
{"id":"30","time":"08:57", "from_id":"2692","text":"To me","to_id":"62"},
{"id":"31","time":"09:28", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"2692","text":"From user1","to_id":"66"}
],
"lastid": "32"
}
var my_id = 2692 /*My chats*/
/*Success JSON request below*/
onSuccess: function(m){
var messages = [];
var chanels = [];
var chanels_u = [];
for(var i=0; i<m.chats.length;i++){
if (my_id != '' && m.chats[i].from_id != parseInt(my_id)){
chanels.push(m.chats[i].from_id);
}
}
chanels_u = chanels.unique(); /*We get id's: 62,66*/
}
My Question:
How can I create a new arrays dynamically (2 for this example for: 62 and 66) and push messages?
To 1 (62):
{"id":"1","time":"13:02", "from_id":"2692","text":"1","to_id":"62"},
{"id":"2","time":"13:48", "from_id":"62","text":"Hello!","to_id":"2692"},
{"id":"12","time":"15:47", "from_id":"2692","text":"3","to_id":"62"},
{"id":"13","time":"15:48", "from_id":"62","text":"4","to_id":"2692"},
{"id":"30","time":"08:57", "from_id":"2692","text":"To me","to_id":"62"}
To 2 (66):
{"id":"31","time":"09:28", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"2692","text":"From user1","to_id":"66"}
Thanks!
You are already identifying your chat ID and pushing it into the chanels array in your code:
if (my_id != '' && m.chats[i].from_id != parseInt(my_id)){
chanels.push(m.chats[i].from_id);
}
You are also identifying unique IDs in your code:
chanels_u = chanels.unique();
All you need to do is locate your chats from the JSON object by comparing them to the IDs in chanels_u and if there's a match, push the text field to the messages array. This is should be close to what you require:
for(var i=0; i<m.chats.length;i++){
for(var j=0; j<chanels_u.length;j++){
if (my_id !== '' && m.chats[i].from_id === chanels_u[j]){
messages.push(m.chats[i].text);
}
}
}
this will do what you want, i believe - create a new object with keys of the to_id and from_id in a way that allows you to loop them whichever way you want. it would probably make more sense to have a toUser and fromUser objects that you can loop independently and cross reference as you build the replies but it's trivial to do so.
var chats = {
"chats":[
{"id":"1","time":"13:02", "from_id":"2692","text":"1","to_id":"62"},
{"id":"2","time":"13:48", "from_id":"62","text":"Hello!","to_id":"2692"},
{"id":"12","time":"15:47", "from_id":"2692","text":"3","to_id":"62"},
{"id":"13","time":"15:48", "from_id":"62","text":"4","to_id":"2692"},
{"id":"30","time":"08:57", "from_id":"2692","text":"To me","to_id":"62"},
{"id":"31","time":"09:28", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"2692","text":"From user1","to_id":"66"}
],
"lastid": "32"
};
var newchats = {}, my_id = 2692;
chats.chats.each(function(chat) {
if (!chat.id || !chat.id.length || chat.from_id == my_id)
return;
newchats["from" + chat.from_id] = newchats["from" + chat.from_id] || [];
newchats["from" + chat.from_id].push(chat);
newchats["to" + chat.to_id] = newchats["to" + chat.to_id] || [];
newchats["to" + chat.to_id].push(chat);
});
console.log(newchats, JSON.encode(newchats));
see on jsfiddle http://jsfiddle.net/dimitar/7j2SN/, outputs:
{
"from62": [{
"id": "2",
"time": "13:48",
"from_id": "62",
"text": "Hello!",
"to_id": "2692"},
{
"id": "13",
"time": "15:48",
"from_id": "62",
"text": "4",
"to_id": "2692"}],
"to2692": [{
"id": "2",
"time": "13:48",
"from_id": "62",
"text": "Hello!",
"to_id": "2692"},
{
"id": "13",
"time": "15:48",
"from_id": "62",
"text": "4",
"to_id": "2692"},
{
"id": "31",
"time": "09:28",
"from_id": "66",
"text": "From user1",
"to_id": "2692"},
{
"id": "32",
"time": "09:29",
"from_id": "66",
"text": "From user1",
"to_id": "2692"}],
"from66": [{
"id": "31",
"time": "09:28",
"from_id": "66",
"text": "From user1",
"to_id": "2692"},
{
"id": "32",
"time": "09:29",
"from_id": "66",
"text": "From user1",
"to_id": "2692"}]
}
I guess, JSON is invalid. You missed to close the JSON properly.
{
"chats": [
{
"id": "1",
"time": "13:02",
"from_id": "2692",
"text": "1",
"to_id": "62"
},
{
"id": "2",
"time": "13:48",
"from_id": "62",
"text": "Hello!",
"to_id": "2692"
},
{
"id": "12",
"time": "15:47",
"from_id": "2692",
"text": "3",
"to_id": "62"
},
{
"id": "13",
"time": "15:48",
"from_id": "62",
"text": "4",
"to_id": "2692"
},
{
"id": "30",
"time": "08:57",
"from_id": "2692",
"text": "To me",
"to_id": "62"
},
{
"id": "31",
"time": "09:28",
"from_id": "66",
"text": "From user1",
"to_id": "2692"
},
{
"id": "32",
"time": "09:29",
"from_id": "66",
"text": "From user1",
"to_id": "2692"
}
]
}
Use JSONLINT to validate your data. You can update(get/set) this array dynamically as you wish.
var msgBox={"chats":[]};
var msg={"id":1,"time":(new Date()).getTime(),"from_id":"","text":"","to_id":""};
var info={ // whole JSON data }
var chats=info['chats'];
for(m in chats){
console.log(chats[m].text) // will display the text
console.log(chats[m].time) // will display the time of chat
chat[m].to_id=32424; // you can modify the to_id value
}
You can make chanels and object instead of array.
onSuccess: function(m){
var messages = [];
var chanels = {};
var chanels_u = [];
for(var i=0; i<m.chats.length;i++){
if (my_id != '' && m.chats[i].from_id != parseInt(my_id)){
var fromID = m.chats[i].from_id;
if(!chanels[fromID]){
chanels[fromID] = [];
}
chanels[fromID].push(m.chats[i]);
}
}
//chanels_u = chanels.unique(); /*We get id's: 62,66*/
}

Categories