json stringify result get value on specific key - javascript

[{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayorder":"6","menuname":"HR Module","menuid":"2","menuurl":""},{"displayorder":"9","menuname":"Administrator","menuid":"1","menuurl":""}]
I have here a stringfy json i want to know how to get a value of all the menuname in this json object any idea appreciated
UPDATE:
I tried this one
here but I get undefined in console
UPDATE
[{"displayorder":"1","menuname":"Menu Management","menuid":"1","submenuurl":"","parentid":"1"},{"displayorder":"1","menuname":"hr sub menu","menuid":"7","submenuurl":"error.php","parentid":"2"},{"displayorder":"2","menuname":"Role Management","menuid":"2","submenuurl":"","parentid":"1"},{"displayorder":"2","menuname":"menu 2 management2","menuid":"8","submenuurl":"","parentid":"2"},{"displayorder":"3","menuname":"hrsubmenu","menuid":"3","submenuurl":"contactus.php","parentid":"2"},{"displayorder":"3","menuname":"submenuaccounting","menuid":"4","submenuurl":"imagegallery.php","parentid":"3"}];
how to get all all details in the second json with parentid depending on above menuid?

Working example:
http://jsfiddle.net/0866pay3/
var json = [{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayorder":"6","menuname":"HR Module","menuid":"2","menuurl":""},{"displayorder":"9","menuname":"Administrator","menuid":"1","menuurl":""}];
json.forEach(function(el, idx){
console.log(el.menuname);
});
Documentation Update
If you check out this article, you'll see the following:
callback is invoked with three arguments:
the element value
the element index
the array being traversed
So, idx is just a common way of representing the element index. You can call this whatever you'd like - theIndex, myRandomName, etc.

var myjson = [{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayorder":"6","menuname":"HR Module","menuid":"2","menuurl":""},{"displayorder":"9","menuname":"Administrator","menuid":"1","menuurl":""}];
var menu_names = [];
for (var x = 0 ; x < myjson.length; x++){
if(myjson[x].hasOwnProperty('menuname')){
// do something usefull here
console.log(myjson[x]['menuname']);
// add value to new array
menu_names.push(myjson[x]['menuname'])
}
}
console.log(menu_names);

Related

Two Dimensional Array - arr[i][0] Gives Wrong Result - JavaScript ASP.NET C#

I have an Array of Arrays populated from C# Model:
var AllObjectsArray = [];
#foreach(var Cobject in Model.ObjectList)
{
#:AllObjectsArray.push(new Array("#Cobject.Name", "#Cobject.Value", "#Cobject.Keyword"));
}
var SelectedObjects = [];
uniqueobj.forEach(function (element) {
SelectedObjects.push(new Array(AllObjectsArray.filter(elem => elem[0] === element))); //makes array of selected objects with their values(name,value,keyword)
});
I am trying to get second parameter of each and every inner Array and add it to new array containing those elements like this:
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][0]) //problem here i think
};
Unfortunately, on:
alert(ValuesArray + " : " + SelectedObjects);
I get nothing for ValuesArray. The other data for SelectedObjects loads properly with all three parameters correctly returned for each and every inner Array,so it is not empty. I must be iterating wrongly.
EDIT:
SOme more info as I am not getting understood what I need.
Lets say SelectedObjects[] contains two records like this:
{ name1, number1, keyword1}
{ name2, number2, keyword2}
Now, what I need is to populate ValuesArray with nane1 and name2.
That is why I was guessing I should iterate over SelectedObjects and get SelectedObject[i][0] where in my guessing i stands for inner array index and 1 stands for number part of that inner array. Please correct me and put me in the right direction as I am guesing from C# way of coding how to wrap my head around js.
However SelectedObject[i][0] gives me all SelectedObject with all three properties(name, value and keyword) and I should get only name's part of the inner Array.
What is happening here?
Hope I explained myself better this time.
EDIT:
I think I know why it happens, since SelectedObjects[i][0] returns whole inner Array and SelectedObjects[i][1] gives null, it must mean that SelectedObjects is not Array of Arrays but Array of strings concatenated with commas.
Is there a way to workaround this? SHould I create array of arrays ddifferently or maybe split inner object on commas and iteratee through returned strings?
First things first, SelectedObjects[i][1] should rather be SelectedObjects[i][0].
But as far as I understand you want something like
var ValuesArray = [];
for (let i = 0; i < SelectedObjects.length; i++) {
for(let j = 0; j <SelectedObjects[i].length; j++) {
ValuesArray.push(SelectedObjects[i][j]);
}
};
In this snippet
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][1]) //problem here i think
};
You're pointing directly at the second item in SelectedObjects[i]
Maybe you want the first index, 0

What is a faster way to write this function to delete rows/objects in a table?

So, I have this function that, after an update, deletes elements from a table. The function, lets call it foo(), takes in one parameter.
foo(obj);
This object obj, has a subfield within called messages of type Array. So, it would appear something like this:
obj.messages = [...];
Additionally, inside of obj.messages, each element contains an object that has another subfield called id. So, this looks something like:
obj.messages = [{to:"You",from:"Me",id:"QWERTY12345.v1"}, ...];
Now, in addition to the parameter, I have a live table that is also being referenced by the function foo. It uses a dataTable element that I called oTable. I then grab the rows of oTable and copy them into an Array called theCurrentTable.
var theCurrentTable = oTable.$('tr').slice(0);
Now, where it gets tricky, is when I look into the Array theCurrentTable, I returned values appear like this.
theCurrentTable = ["tr#messagesTable-item-QWERTY12345_v1", ...];
The loop below shows how I tried to show the problem. While it works (seemingly), the function itself can have over 1000 messages, and this is an extremely costly function. All it is doing is checking to see if the current displayed table has the elements given in the parameter, and if not a particular element, delete it. How can I better write this function?
var theCurrentTable = oTable.$('tr').slice(0);
var theReceivedMessages = obj.messages.slice(0);
for(var idx = 0; idx < theCurrentTable.length; idx++){ // through display
var displayID = theCurrentTable[idx].id.replace('messagesTable-item-','').replace('_','.');
var deletionPending = true;
for(var x = 0; x < theReceivedMessages.length; x++){
var messageID = theReceivedMessages[x].id;
if(diplayID == messageID){
console.log(displayID+' is safe...');
deletionPending = false;
}
}
if(deletionPending){
oTable.fnDeleteRow(idx);
}
}
I think I understand your problem. Your <tr> elements have an id that should match an item id within your messages.
First you should extract the message id values you need from the obj parameter
var ids = obj.messages.map(function (m) { return '#messagesTable-item-' + m.id; });
This will give you all the rows ids you need to keep and then join the array together to use jQuery to select the rows you don't want and remove them.
$('tr').not(ids.join(',')).remove();
Note: The Array.prototype.map() function is only supported from IE9 so you may need to use jQuery.map().
You could create a Set of the message ID values you have, so you can later detect if a given ID is in this Set in constant time.
Here is how that would look:
var theCurrentTable = oTable.$('tr').slice(0);
var theReceivedMessages = obj.messages.slice(0);
// Pre-processing: create a set of message id values:
var ids = new Set(theReceivedMessages.map( msg => msg.id ));
theCurrentTable.forEach(function (row, idx) { // through display
var displayID = row.id.replace('messagesTable-item-','').replace('_','.');
// Now you can skip the inner loop and just test whether the Set has the ID:
if(!ids.has(displayId)) {
oTable.fnDeleteRow(idx);
}
});
So now the time complexity is not any more O(n.m) -- where n is number of messages, and m the number of table rows -- but O(n+m), which for large values of n and m can make quite a difference.
Notes:
If theCurrentTable is not a true Array, then you might need to use a for loop like you did, or else use Array.from(theCurrentTable, function ...)
Secondly, the implementation of oTable.fnDeleteRow might be that you need to delete the last rows first, so that idx still points to the original row number. In that case you should reverse the loop, starting from the end.

How to get the value from JSON in JS

I'm trying to get the "formatted_address" value from this
JSON file. I'm new to this and found the documentation quite confusing. The code I have now is the following where the variable "location" is the url generated like the one above.
$.getJSON(location, function( data ){
stad = data.results.formatted_address;
console.log(stad);
});
How would I achieve this?
results is an array, so you need to access it as one. Given your example with only one item, you can access it directly by index:
var stad = data.results[0].formatted_address; // = "'s-Hertogenbosch, Netherlands"
If there were multiple items in the array you would need to loop through them:
for (var i = 0; i < data.results.length; i++) {
var stad = data.results[i].formatted_address;
// do something with the value for each iteration here...
}
$.each(data.results,function(key,value){
console.log(value.formatted_address); //'s-Hertogenbosch, Netherlands
});

Why doesn't my variable save to my array in JavaScript?

Hello I have a piece of code that checks a value against an array and if that value is not found in the array, then it adds that value to another array (called the soldListingArray). It then saves the soldListingArray to the localStorage (using localStorage.setItem("array", soldListingArray). For some reason, in my console I can see that the variable is the correct one, after adding it to the array, but outside of the code when I call for the entire array, it says it's empty.
array1 is the array I'm checking all the values inside against the array2 array.
Here is my code:
function checkToSeeIfListingIsSold() {
var soldListingArray = localStorage.getItem("array");
var x = 0;
var y = array1.length;
do {
var index = array1[x];
if (array2.indexOf(index) == -1) {
// Here I add the variable to my soldListingArray
soldListingArray[soldListingArray.length] = index;
// Here my console says what has been added to the soldListingArray (the value is correct).
console.value += index + " has been added to soldListingArray;\n";
}
x++;
} while (x < y)
localStorage.setItem("array", soldListingArray);
// Here I ask my console to display my soldListingArray but I get an empty array back.
console.value += "Sold Array: " + soldListingArray;
}
Why wasn't the index variable added and saved to my soldListingArray?
Any help is appreciated! Thanks in advance.
You need to convert the array to a string if you want to use local storage:
localStorage.setItem("array",JSON.stringify(soldListingArray))
Then when you need to access it later and add items, you convert it back to an array:
soldListingArray = JSON.parse(localStorage.getItem("array"));
This has been answered before; a little research would go a long way:
Storing Objects in HTML5 localStorage

Cannot access second field in a 2 dimension array in javascript

I have a 2 dimension array defined as
var thischart = [[],[]];
and the array contains the following data created programatically:
1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,24,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0
I cannot get the single value of the second field in the particular array cell. For example, if I use the following command to get the value:
alert("thischart[i,1]=" + thischart[0, 1]);
I get the following answer:
thischart[i,1]=2,0
I tried using the second dimension to access the data as
thischart[0][1]);
but it gives me an error message:
I just want to get the second single value in the array such as for array cell 13 I want the value 24 from above. Does anyone have an answer on how to access this array?
I populated the array as follows and then updated it thru program logic:
$hours = [];
for($i = 0; $i< 24; $i++){
$hours[$i] = [];
$hours[$i][0] = ($i + 1);
$hours[$i][1] = "0";
}
And the answer to this question is below:
for(var i in thischart){
var tc = thischart[i];
myvalue = tc[1]); // this is the value I want
}
Thanks to everyone who responded.
For all of them like this:
for(var i in thischart){
var tc = thischart[i];
for(var n in tc){
// n is internal index
// tc[n] is internal value
}
}
For a single value from the first internal Array, the second value:
thischart[0][1];
Why don't you use the console to see what's the return of
thischart[0];
Because it should contain an array. If it does, then
thischart[0][1];
is perfectly valid syntax. And if it doesn't, then
thischart[0,1]
means nothing whatsoever.
Do something like this:
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1
do you mean something like this:...
http://jsfiddle.net/DSrcz/1/
var arr = [1,0,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0];
arr[33]=1000;
alert(arr[13]);
alert(arr[33]);

Categories