Angular extract data from JSON corresponding to Key - javascript

Below is the JSON i received from server.
Now i am having variable public checkId: any = 54
How to extract data corresponding to ID = 54 from below JSON ??
I want to extract below that is mentioned against KEY 54
"Increase Again": true,
"Decrease Previous" : true,
"Like" : true,
"Dislike" : true,
"Old Again" : false,
"Others" : true
Below is the JSON from which i have to extract above data
{
"27" : {
"Increase": true,
"Decrease" : true,
"Like" : true,
"Dislike" : true,
"Old" : false,
"Others" : true
},
"54" : {
"Increase Again": true,
"Decrease Previous" : true,
"Like" : true,
"Dislike" : true,
"Old Again" : false,
"Others" : true
},
"104" : {
"Increase Previous": true,
"Decrease Prior" : true,
"Like" : true,
"Dislike" : true,
"Old" : false,
"Others Check" : true
}
}
Thanks in advance ...
#Edit - The key are not simply 1,2,3 they are specific Id 53,54,55 also it can 100, 108, 4657

You can simply get the specific element by passing the checkId in your response, For instance I'm assuming that you have that JSON in result variable.
You can call it in the following way
let result = //Your json;
let checkId = 2;
result[checkId] ==> This will return 2nd object of JSON

You Can get Ur Desired Value simply like this..
let checkId = 2;
let data = {
"1": {
"Increase": true,
"Decrease": true,
"Like": true,
"Dislike": true,
"Old": false,
"Others": true
},
"2": {
"Increase Again": true,
"Decrease Previous": true,
"Like": true,
"Dislike": true,
"Old Again": false,
"Others": true
},
"3": {
"Increase Previous": true,
"Decrease Prior": true,
"Like": true,
"Dislike": true,
"Old": false,
"Others Check": true
}
}
let result = data[checkId]
console.log(result)

Related

Javascript updates entire column in boolean matrix

I'm trying to update a specific index in a boolean matrix but it update the entire column. what might be the problem?
I'm attaching the code here:
const booleanMatrix = Array(5).fill(Array(5).fill(false));
console.log(booleanMatrix);
booleanMatrix[0][0] = true;
console.log(booleanMatrix);
first and second prints:
[
[ false, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ]
]
[
[ true, false, false, false, false ],
[ true, false, false, false, false ],
[ true, false, false, false, false ],
[ true, false, false, false, false ],
[ true, false, false, false, false ]
]
I expect it to be:
[
[ true, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ]
]
Your code is equivalent to:
const inner = Array(5).fill(false);
const booleanMatrix = Array(5).fill(inner);
Of course when you update inner, it updates on each row, since each row is pointing to the same thing.
You need to do
let x = Array(5).fill(null).map((i) => Array(5).fill(false));
console.log(x);
x[0][0] = true;
console.log(x);
const booleanMatrix = Array(5).fill(Array(5).fill(false));
This fills an array with 5 references to the same array.
Array(5).fill(false) // reference to one array
When you change one array, you're changing all of them, because they're all the same object in memory.
You need to create 5 different arrays and load each one of them:
let booleanMatrix = [
Array(5).fill(false),
Array(5).fill(false),
Array(5).fill(false),
Array(5).fill(false),
Array(5).fill(false)
];
Alternatively:
let booleanMatrix = Array(5).fill("throwAway").map( () => Array(5).fill(false));
This will create 5 unique arrays

Firebase load all data from uid

Let's say I have a big list of items where the user can go and favourite items as they wish. These favourites then go to a new node userLikedItems/userUID/.
When saving favourites, I am trying to figure out the best way to do so:
Here is my current, duplicative approach:
//duplicating all the data when a user favourites an item into their own node under userLikedItems
{
"hwUjzftGyCgMrRgNv4Djg5F4ZCQ2" : {
"24K Carrot" : {
"effects" : {
"Euphoria" : true,
"Happy" : true,
"Relaxing" : true,
"Sleepy" : true
},
"medical" : {
"Arthritis" : true,
"Bipolar Disorder" : true,
"Chronic Pain" : true,
"Depression" : true,
"Fatigue" : true,
"Inflammation" : true,
"Insomnia" : true,
"Loss of Appetite" : true,
"Migraines" : true,
"PTSD" : true,
"Stress" : true
},
"levels" : "18% - 24%",
"title" : "24K Carrot",
"titleLowercase" : "24k Carrot",
"uid" : "24K Carrot"
},
"2 Pac" : {
"effects" : {
"Cerebral" : true,
"Focus" : true,
"Happy" : true,
"Horny" : true,
"Relaxing" : true,
"Uplifting" : true
},
"medical" : {
"Arthritis" : true,
"Cramps" : true,
"Depression" : true,
"Gastrointestinal Disorder" : true,
"Loss of Appetite" : true,
"Migraines" : true
},
"levels" : "29%",
"title" : "2 Pac",
"titleLowercase" : "2 pac",
"uid" : "2 Pac"
},
}
}
Here is the next approach where I am trying to determine if it is a better practice than my current approach:
//data stored with only uid:true under user's favourites node
{
"hwUjzftGyCgMrRgNv4Djg5F4ZCQ2" : {
"24K Carrot" : true,
"2 Pac" : true,
"Triple Take" : true,
}
// fetching the rest of the data inside list item
componentDidMount() {
firebase.database().ref('/userLikedItems').child(this.props.user.item.uid).once('value', snapshot => {
const itemData = snapshot.val();
this.setState({
name: itemData.name,
image: itemData.image,
type: itemData.type
});
});
}
So basically when a list item is mounted I am calling this query to fetch the rest of the data. I am worried this is a bad practice.
Right now I am currently duplicating all the item data in the userLikedItems node which means I would not have to perform that query for every item, instead I would simply load all the data from the users node - the problem with this is I have to use a cloud function to keep the data consistent when the main item changes and there is a lot of duplicate data in my database when it could instead just be a simple boolean for each item.
I appreciate all the feedback!
Cheers.

How to hide a particular column from the datatable?

I'm building a page where I need to display a datatable.
Based on a condition, this table should display either 5 or 6 columns.
This is my code in .js file to display the table with 6 columns:
if(Display)
{
myself.set_DataTable(myself._findjcontrol("tTable1"));
myself.get_DataTable().dataTable(
{
"sDom": '<"top">rt<"bottom"flp><"clear">',
"aoColumns": [
{ "sType": "string" }, //Column1
{"sType": "string" }, //Column2
{"sType": "string" }, //Column3
{"sType": "string" }, //Column4
{"sType": "string" }, //Column5
{"sType": "html"} //Column6
],
"bPaginate": false,
"bAutoWidth": false,
"bJQueryUI": false,
"bFilter": false,
"bPage": false,
"bSort": false,
"binfo": false,
"bSortClasses": false
});
}
else
{
myself.set_DataTable(myself._findjcontrol("tTable_2"));
myself.get_DataTable().dataTable(
{
"sDom": '<"top">rt<"bottom"flp><"clear">',
"aoColumns": [
{ "sType": "string" }, //Column1
{"sType": "string" }, //Column2
{"sType": "string" }, //Column3
{"sType": "string" }, //Column4
{"sType": "string" } //Column5
],
"bPaginate": false,
"bAutoWidth": false,
"bJQueryUI": false,
"bFilter": false,
"bPage": false,
"bSort": false,
"binfo": false,
"bSortClasses": false
});
}
Based on a condition, I'm repeating the code twice. Is there a way to defined some kind of property for the column, so, based on condition, I change that property and append it to a column definition. Something like this:
var isDisplay = false;
if(Display)
{
isDisplay = true;
}
else
{
isDisplay = false;
}
/* the rest of code */
{"sType": "string", isDisplay } //Column5
/* the rest of code */
Is that possible to do something like that?
If I correctly understood what you need, you can separate your settings with variables without repeating code:
var control = "tTable_2"
, columns = [
{ "sType": "string" }, //Column1
{"sType": "string" }, //Column2
{"sType": "string" }, //Column3
{"sType": "string" }, //Column4
{"sType": "string" } //Column5
];
if(Display)
{
columns.push({"sType": "html"}); //Column6
control = "tTable_1";
}
myself.set_DataTable(myself._findjcontrol(control));
myself.get_DataTable().dataTable(
{
"sDom": '<"top">rt<"bottom"flp><"clear">',
"aoColumns": columns,
"bPaginate": false,
"bAutoWidth": false,
"bJQueryUI": false,
"bFilter": false,
"bPage": false,
"bSort": false,
"binfo": false,
"bSortClasses": false
});
Also, it seems there's a feature in DataTable that could help you. Try to use the property bVisible in the column you want to hide/show:
myself.set_DataTable(myself._findjcontrol("tTable1"));
myself.get_DataTable().dataTable(
{
"sDom": '<"top">rt<"bottom"flp><"clear">',
"aoColumns": [
{ "sType": "string" }, //Column1
{"sType": "string" }, //Column2
{"sType": "string" }, //Column3
{"sType": "string" }, //Column4
{"sType": "string" }, //Column5
{"sType": "html", "bVisible": Display} //Column6
],
"bPaginate": false,
"bAutoWidth": false,
"bJQueryUI": false,
"bFilter": false,
"bPage": false,
"bSort": false,
"binfo": false,
"bSortClasses": false
});
Hope it helps.

Disable drag and drop of columns in jquery Datatable

I am using JQuery Datatables Plugin (datatable). I want to disable reordering of columns,
Below is my code.
.DataTable({
"serverSide" : true,
"bFilter": false,
"bInfo": false,
responsive: true,
sDom: "Rlfrtip",
"pagingType" : "simple_numbers",
"pageLength" : 10,
"bLengthChange" : false,
"drawCallback":enableTimer(trainingTableRefreshFrequency),
"ajax" : {
"url" : getAllTraniningServiceUrl,
"data" : function(d) {
d.searchKey=$("#searchKey").val();
d.searchValue=$("#searchValue").val();
},
type : 'POST'
},
"language": {
"emptyTable": "No Data Available"
},
"columns" : [ {
"orderable" : false,
"searchable" : false,
"data" : null,
]
});
What are the ways to disable reordering of columns.

Can't get saveRow aftersavefunc or successFunc to work

I've got some code that, when switching which row is selected, it triggers a save of the previously selected row.
The row is being successfully saved without any problem, however the successfunc isn't being called at all - my console.log output never shows up, and the code in this function isn't being run. I also tried specifying the function as the aftersavefunc, but couldn't get that to work either.
Seems like a simple syntax problem, but I can't quite get it right. Am I not specifying this function properly?
As a side note, I realize that reloading the entire grid after a row save seems like overkill, but in the context of where this particular piece of code is, within the larger structure of my app, this snippet of code is a special case.
The full jqGrid code is:
var lastSelectedMainGridRowID = 0;
var lastSelectedSubGridRowID = 0;
var translationsFeed = "/update/translations/ajax/translations_feed.php";
var translationsEdit = "/update/translations/ajax/translations_edit.php";
var translationsSubGridFeed = "ajax/translations_subgrid_feed.php";
var translationsSubGridFeedEdit = "ajax/translations_subgrid_feed_edit.php";
$(document).ready(function () {
$("#translationsList").jqGrid({
caption : "Translations",
datatype : "xml",
url : translationsFeed,
editurl : translationsEdit,
mtype : "get",
pager : "#translationsPager",
rowNum : 20,
autowidth : true,
sortname : "phrase",
sortorder : "asc",
viewrecords : true,
multiselect : false,
hidegrid : false,
height : 300,
altRows : true,
rownumbers : true,
toolbar : [false],
loadComplete: function(data) {
jQuery("#translationsList").setSelection (0, true);
},
colNames : ["phrase_id", "translation_id", "language_cd", "Phrase", "Translation", "Modified", "Created", "Active"],
colModel : [
{ name : "phrase_id", index : "phrase_id", sortable : true, search : false, editable: true, edittype : "text", editrules: { edithidden: true }, hidden: true},
{ name : "translation_id", index : "translation_id", sortable : false, search : false, editable: true, edittype : "text", editrules: { edithidden: true }, hidden: true},
{ name : "language_cd", index : "language_cd", sortable : true, search : true, editable: true, edittype : "text", editrules: { edithidden: true, required : true }, hidden: true },
{ name : "Phrase", width:200, index : "phrase", sortable : true, search : true, editable: true, edittype : "text", editrules: { required: true } },
{ name : "Translation", width:200, index : "translation", sortable : true, search : true, editable: true, edittype : "text", editrules: { required: false } },
{ name : "Modified", width:100, index : "modify_dt", sortable : true, search : true },
{ name : "Created", width:100, index : "create_dt", sortable : true, search : true },
{ name : "Active", width:20, index : "active", sortable : true, search : true, editable: true, edittype: "checkbox", editoptions: {value:"Yes:No", checked: true} }
],
onSelectRow: function(id) {
jQuery('#translationsList').jqGrid('saveRow', lastSelectedMainGridRowID);
jQuery('#translationsList').jqGrid('editRow', id, true);
lastSelectedMainGridRowID = id;
},
subGrid: true,
subGridRowExpanded: function(subgrid_id, row_id) {
var subgrid_table_id;
jQuery("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table>");
jQuery("#"+subgrid_table_id).jqGrid({
url: translationsSubGridFeed + "?phrase_id=" + row_id,
editurl: translationsSubGridFeedEdit,
datatype: "xml",
colNames: ['phrase_id', 'translation_id', 'language_cd', 'Translations', 'Language', 'Active'],
colModel: [
{name:"phrase_id", index:"phrase_id", sortable: false, editable: true, edittype : "text", editrules: { edithidden :true }, hidden: true},
{name:"translation_id", index:"translation_id", sortable: false, editable: true, edittype : "text", editrules: { edithidden :true }, hidden: true},
{name:"language_cd", index:"language_cd", sortable: false, editable: true, edittype : "text", editrules: { edithidden :true }, hidden: true},
{name:"Translation", index:"translation", sortable: true, editable: true, edittype:"text", width:589},
{name:"Language", index:"language_disp", sortable: true, editable: false, width:250},
{name:"Active", index:"active", sortable: true, editable: true, edittype:"checkbox", editoptions:{value:"Yes:No", checked: true}, width:80}
],
height: "100%",
rowNum:20,
sortname: 'language_cd',
sortorder: "asc",
onSelectRow: function(id) {
jQuery("#"+subgrid_table_id).jqGrid('saveRow', lastSelectedSubGridRowID, function(response) {
console.log("Data: " + response.responseText);
return false;
});
jQuery("#"+subgrid_table_id).jqGrid('editRow', id, true);
lastSelectedSubGridRowID = id;
}
});
}
});
Perhaps I don't need to use saveRow. In this case, what I'm doing is:
When you click on a row, it becomes editable
If you then click on a second row, the first row is saved (and no longer selected), and the new second row then becomes editable. Similar to saving a row "onBlur", so to speak.
I don't see the place of code where responseData variable are defined. The code responseData[0] should throw an exception, so the console.log("Data: " + responseData[0]); will not display any data. The line of code should be probably fixed as
console.log("Server response: " + result.responseText);
UPDATED: Without having the data for the both grid and for example the subgrid corresponds the first row one can't debug the code. Reading is not so effective. If you posted the test data (two XML files) I could try to localize the problem.
An important error is that you only declare subgrid_table_id variable, but not assign a value for it. Typically one construct an unique id name subgrid_table_id based on the subgrid_id. For example
var subgrid_table_id = subgrid_id+"_t";
instead of var subgrid_table_id; only.
Nevertheless some things I find a little suspected:
I don't understand why you return return false; from the successfunc. It means that you interpret the server response as an error and the normal actions on successful server response should be interrupted. I would recommend you additionally use errorfunc parameter of saveRow. In my server code the server always return error HTML status code in case of the server error. So I never need use successfunc and use aftersavefunc and errorfunc only.
The subgrid has many column which already exist in the corresponding row of the parent grid. The potential problems here are not only spending of additional memory. You don't posted the grid data and so I don't know what values you use as rowids for grids. It is very important to have no id duplicates on the HTML page. So you should be careful in the subject. Why you need ? Probably you can just use extraparam parameter of saveRow and editRow instead of the usage of phrase_id, translation_id and language_cd hidden columns having editable: true, editrules: { edithidden :true }, hidden: true properties?

Categories

Resources