Cycling through jquery object to get its values - javascript

I have to loop through the object and get all its values. Here's an image of object
So, basically i have to get classificatorCodeId and loop through observationList to get its child classificatorCodeId's and observationLists, and so on.
If you guys have any ideas, what's the best way to loop through this object, id be happy to try your solutions.

Following code will print all values in that object as key --> value pairs
var traverse = function(mainObject)
{
$.each(mainObject, function(index, subObject)
{
if(($.type(subObject) === "object" || $.type(subObject) === "array"))
{
traverse(subObject);
}
else
{
console.log(index+" --> "+subObject);
}
});
}
traverse(mainObject);

Related

Displaying only the first item from the localStorage data array

I am trying to build a board that should display the first number from the list but I can't find $.each alternative.
Currently, I have a piece of code that displays all items from the localStorage. Does anyone have an idea of jQuery function that would take an array as argument and callback only the first item? Similar to this one - $.each( array, callback ).
const clients = JSON.parse(localStorage.getItem("data"));
const odontologas = clients.Odontologas;
$.each(odontologas, function(i, item) {
if (item.Būsena === "Eilėje") {
$("#odontologasQueue").append(
`<p class="boardNumber">${item.EilėsNr}</p>`
);
} else {
$("#odontologasQueue").append(`<p class="boardNumber">000</p>`);
}
});
Just needed to add return false to if statement.
So either exit the loop when you find the match or use array.find
var first = odontologas.find(item => item.Būsena === "Eilėje")
// var first = odontologas.find(function(item) { return item.Būsena === "Eilėje" })
console.log(first)
Long story short, you want index of an entry? It's
odontologas.indexOf("Eilėje"); // equals -1 if element isn't found in the array

Using Javascript Array Filter method to apply logic [duplicate]

I have search through quite a lot of questions here, but havent found one that i think fits my bill, so if you know of one please link to it.
I have an array that i want to search through for a specific number and if that number is in the array, i then want to take an action and if not then another action.
I have something like this
var Array = ["1","8","17","14","11","20","2","6"];
for(x=0;x<=Array.length;x++)
{
if(Array[x]==8)
then change picture.src to srcpicture1
else
then change picture.src to srcpicture2
}
but this will run the lenght of the array and end up checking the last element of the array and since the last element is not 8 then it will change the picture to picture2.
Now i can see why this happens, i just dont have any ideas as to how to go about checking if an array contains a specific number.
Thanks in advance.
What you can do is write yourself a function to check if an element belongs to an array:
function inArray(array, value) {
for (var i = 0; i < array.length; i++) {
if (array[i] == value) return true;
}
return false;
}
And the just do:
var arr = ["1","8","17","14","11","20","2","6"];
if (inArray(arr, 8)) {
// change picture.src to srcpicture1
} else {
// change picture.src to srcpicture2
}
It's a lot more readable to me.
For extra points you can add the function to the array prototype like so:
Array.prototype.has = function (value) {
for (var i = 0; i < this.length; i++) {
if (this[i] === value) return true;
}
return false;
};
And then the call would be
if (arr.has(8)) // ...
Pushing this even further, you can check for indexOf() method on array and use it - if not - replace it with the code above.
P.S. Try not to use Array for a variable name, since it's reserved for the actual array type.
use this
http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf
ie version
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf#Compatibility
Why don't just you abort the loop when you find the right number :
for(x=0;x<=Array.length;x++)
{
if(Array[x]==8) {
//change picture.src to srcpicture1
break;
}
}
You could sort the array first then check the array only up to the point at which a number would be in the array, were it to exist.
If you have unique keys and a faster retrieval is what you care about a lot, you can consider using a map instead of an array (if there's a hard-bound case of using an array, then it won't work of course). If using a map, you just check "if( num in arr ) ".

How to splice item from array in javascript

I am looking a way to delete all elements from array if target object attribute is present in array.
var msg={name:'tar', type:'SR'}; //want to delete all object with type=SR
var items= [{name:'oh', type:'SR'},{name:'em', type:'PR'},
{name:'ge', type:'MR'},{name:'ohoo', type:'SR'}];
items.splice( items.indexOf(msg.type), 1 );
In this way only one object is deleting. Can someone suggest a better way that without using a loop i can delete all the target object from array
You can try something like following
items = items.filter(function(item){
return item.type !== msg.type;
});
a bit of functional and it's done:
var result = items.filter(function(item){
return (item.type == msg.type) ? false : true;
});

How to compare the values of a particular key from both arrays using inArray in jQuery

I have two array with objects inside in it. I want to compare the values of a particular key from both arrays and do something with that. I have tried using inArray but couldn't succeed. Below is my code.
function initialize() {
geometry = 'http://yyyy.cartodb.com/api/v2/sql?q=SELECT name,ST_AsGeojson(the_geom) from msa_usa';
$.getJSON(geometry,
function(data) {
var place_names = [];
place_names.push({
name: "Abilene",
average: 8.65
});
for (i = 0; i < place_names.length; i++) {
if ($.inArray(data.rows[i].name, place_names[i].name) > -1) {
geom.push((data.rows[i].st_asgeojson));
average_value.push(place_names[i].average);
} else
(console.log("else"));
//console.log(place_names[i].name);
}
})
}
console.log(average_value.length);
console.log(geom.length);
I'm not sure why you're trying to use $.inArray() at all. It appears you're just trying to compare two properties on two objects (which happen to be in arrays, but you're already indexing to a particular object). If that's the case, then you can just directly compare the two properties:
if (data.rows[i].name === place_names[i].name)
But, in your code, you appear to have just created place_names so it will only have one value in it, not a whole bunch of values in it. So, now that confuses me as to what you're really trying to do here.
For more help, please describe in words what you're really trying to accomplish. Are you just trying to see if one particular .name property is in the data.rows array of objects?
If so, that would be a different piece of code like this:
function findPropInArray(array, propName, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][propName] === value) {
return i;
}
}
return -1;
}
Then, in your code you could use something like this:
if (findPropInArray(data.rows, "name", "Abilene") !== -1) {
// "Abilene" was as a name property in data.rows
}

Is there a way to prevent undefined javascript variables from displaying 'undefined' when inserted into html?

I am appending text which is stored in a javascript variable into a div element. The issue is that the depending on the situation there may or may not be text stored in that variable. If there is not I end up with the text 'undefined' where the valid text would have been in the div.
so as an example:
htmlelement.innerhtml = '<h2>'+array.object.title+
'</h2><p>'+array.object.textField1+
'</p><p>'+array.object.textField2+
'</p><p>'+array.object.textfield3+'</p>';
This shows up in a function which will run for each object in the array. Not all of the objects have content in all 3 text fields.
So is there an easy way to prevent 'undefined from being printed?
Right now I have this before the previous line:
if (!array.object.textfield1) {
array.object.textfield1 = ' ';
}
if (!array.object.textfield2) {
array.object.textfield2 = ' ';
}
if (!array.object.textfield3) {
array.object.textfield3 = ' ';
}
But this is not a practical solution if there are a lot of variables that need to be checked.
Can you use the logical operator || ?
array.object.textField1||''
Note: Please do take care of values like 0 or any other falsy values .
Use "The New Idiot" answer this is here just fro an extra method.
The other answer is better because it molds the check into the logic ( a good thing!) and is better for performance.
with that said REGEX!!
htmlelement.innerText = htmlelement.innerText.replace('undefined', '');
check each array item to see if its undefined with the **typeof** operator.
for each array item if the **typeof** is **undefined** you can do eather 2 things:
1. set to default
2. remove with splice()
example:
function cleanArray(theArray){
for(i=0;i < theArray.length;i++){
if(typeof theArray[i] == "undefined"){
theArray[i]="";//OR SPLICE IT OU WITH splice()
}
}
}
//NOW CALL THIS FUNCTION EVERYTIME PASSING IT THE ARRAY
cleanArray(arrayOfItems);
no simple way around this, you need to plan your design accordingly
"The New Idiot" answer is pretty good if you only have a few. If you have a more complicated object that you want to sort out, one option would be to iterate over the properties and set them to an empty string if they are undefined. e.g.
var o = {
t1: undefined,
t2: "hey"
};
for (prop in o) {
if (o.hasOwnProperty(prop) && typeof o[prop] === "undefined") {
o[prop] = "";
}
}
jsFiddle: http://jsfiddle.net/Ca6xn/

Categories

Resources