I have an array of objects in JavaScript. e.g. current_films[0].f_name, current_films[0].f_pattern etc. I want to copy the array into another similiar to the following:
for(var i=0; i<current_films.length; i++)
{
if(current_films[i].f_material == Value)
{
temp[i] = current_films[i];
}
}
However, there seems to be an inexplicable problem when I do this. By inexplicable problem, I mean that the code does not execute and the array is not copied as I desire.
Any help would be greatly appreciated.
Thank you!
P.S. Could you please mention why the above code would not work? As in, if I put an alert("Reached here");, it's not getting executed. Any ideas why its so?
One problem I see is that you set temp[i] to the value which means there would be gaps in the temp array. You could use push() to append the value to temp so you don't need to manage two sets of indices.
You could also use JavaScript's Array.filter() to do this a little easier. Filter will return a new array of the values from the original array where your function returns true.
var temp = current_films.filter(function(film) {
return (film.f_material === Value);
});
P.S. Could you please mention why the above code would not work? As in, if I put an alert("Reached here");, it's not getting executed. Any ideas why its so?
I'd guess f_material is not defined for every element in the array.
If that's the case I'd use
if(typeof(current_films[i].f_material)!=='undefined')
{
if(current_films[i].f_material == Value)
{
temp[i] = current_films[i];
}
}
Anyway I'd suggest you to get familiar with the browser's javascript debugger (assumed that code runs in a browser)
Finally note that you're not copying the array/object:
temp[i] is a reference to current_films[i]
Modifying current_films later in the code will result in modifying temp
If that's not the behaviour desired Google for "javascript object copy".
Related
Example:
When I check a variable containing this value [""] it returns false.
var th=[]
th.push("");
if($("#multiselect").val()==th)
It returns always false.
Thank you.
Edit 1:
changed Var to var. It was a typo.
Edit 2:
Actually, the problem I faced was I was trying to get the value from a multi-select input. The multi-select input sometimes returns values as [""] even I haven't selected any values basically it's a plugin. So I was confused and I thought [""] is a fixed primitive value like 1, 10, "bla blah",.. So I tried to compare it with the same array as the right-hand side of the '=' operator.
It was stupid. Now I posted the solution to my problem and I explained my stupidity.
there are two things:
Change Var to var
You can use includes method of Array as:
var th = [] <==== chnage Var to var
th.push("");
if(th.includes($("#multiselect").val())) { <=== you can use includes method of array
// DO whatever you want
}
Make sure var is lowercased.
You are accessing th as an array, so you’ll need to specify the index of the value you are checking: th[0]
Use triple equals, too: .val()===th[0]
Double check the jquery docs if you’re still running into trouble.
Happy coding!
A couple of things to consider:
You have a typo in the code above; var is valid; Var is invalid.
Browser will aptly complain to solve this typo.
You are comparing an array to DOM value; this will always be false.
DOM is a costly process. Unless the value associated is dynamic, its better to read once, store value into a variable and continue processing instead of reading from DOM always.
You could choose to try something on these lines:
let arr = [1,2,3,4];
let domValue = $("#multiselect").val();
arr.push(5);
arr.map((el, ix) => {
if el === domValue return true; //or choose to do something else here.
});
var th=[]; //It is var not Var
th.push("");
if($("#multiselect").val()==th[0]) // change th to th[0]
I am unable to comment so having to use an answer for now. Are you trying to check if an array has any values? If so you can use
if(th.length){
// do something
}
If you want to check a normal variable for empty string you can simply use
if(th == “”){
//do something
}
I found the solution after a couple of days when I posted this question. Now I can feel how stupid this question was.
Anyway, I'm answering this question so it might help others.
Answer to my question:
When two non-primitive datatype objects(which is the Array here) are compared using an assignment operator, it compares its reference of the object. So the object creation of both arrays would be different. If I want to check the array has [""] value, I should do something like the below.
function isArrValEmptyCheck(value) {
return !value || !(value instanceof Array) || value.length == 0 || value.length == 1 && value[0] == '';
}
console.log(isArrValEmptyCheck([""]));//returns true
console.log(isArrValEmptyCheck(["value1"]));//returns false
Sorry for the late response. Thanks to everyone who tried to help me.
I'm terribly new to javascript and I tried to foreach through members of an array to see if they are empty, but couldn't quite figure out how to do it, I've tried several ways already.
So here is the json array:
var myArray = {
a:document.getElementById('id').value,
b:document.getElementById('password').value,
};
and here is my attempt at checking if respective members of that array is empty:
for (var check in myArray) {
if((check == null)||(check.length===0)||(check=='')){
console.log("empty member found!");
break;
}else{console.log(check);}
}
as it turned out it passes the check every time and when it prints out check, it prints out only a, b in the browser console, not its value as I had expected.
I know I must've made several entry-level mistake but how should I fix it?
So as CertainPerformance pointed out, you can't really use:
if((check == null)||(check.length===0)||(check==''))
instead, I used:
if((emptyCheckArray[check] == null)||(emptyCheckArray[check].length===0)||(emptyCheckArray[check]==''))
and it did the trick! Note that my code may be redundant, but hey, safe > sorry!
The best way to explain this is just to show you.
var condition = 70;
var formnames = new Array("wheelcheckbox1", "wheelcheckbox2","spokecheckbox","spokecheckbox2","tirecheckbox","tirecheckbox2","tirecheckbox3");
formnames.forEach(function(entry) {
console.log(obj.entry);
if(obj.entry == "") {
condition = condition - 10;
}
});
as you can see I used the console log to show how it needs to work
as that works perfect, however, using the array causes an error as
they're strings and not what the obj wants, it wants text without it being a string.
Any ideas?
for..in should not be used to iterate over an array. Consider using forEach instead.
I'm creating a few specific functions for a compiler I'm working on, But certain restrictions within the compiler's nature will prevent me from using native JavaScript methods like Array.prototype.pop() to perform array pops...
So I decided to try and write some rudimentary pseudo-code to try and mimic the process, and then base my final function off the pseudo-code... But my tests seem to fail... based on the compiler's current behavior, it will only allow me to use array.length, array element assignments and that's about it... My code is below...
pop2 = function(arr) {
if(arr.length>0){
for(var w=undefined,x=[],y=0,z=arr.length;y<=z;y++){
y+1<z?(x[y]=arr[y]):(w=arr[y],arr=x);
}
}
return w;
}
Arr = [-1,0,1,2];
// Testing...
console.log(pop2(Arr)); // undefined... should be 2
console.log(Arr); // [-1,0,1,2]... should be [-1,0,1]
I'm trying to mimic the nature of the pop function but can't seem to put my finger on what's causing the function to still provide undefined and the original array... undefined should only return if an initial empty array is sent, just like you would expect with a [].pop() call...
Anyone have any clues as to how I can tailor this code to mimic the pop correctly?
And while I have heard that arr.splice(array.length-1,1)[0]; may work... the compiler is currently not capable of determining splice or similar methods... Is it possible to do it using a variation of my code?
Thanks in advance...
You're really over-thinking [].pop(). As defined in the specs, the process for [].pop() is:
Get the length of the array
If the length is 0
return undefined
If length is more than 0
Get the item at length - 1
Reduce array.length by 1
Return item.
(... plus a few things that the JavaScript engine needs to do behind the scenes like call ToObject on the array or ensure the length is an unsigned 32-bit integer.)
This can be done with a function as simple as the one below, there's not even a need for a loop.
function pop(array) {
var length = array.length,
item;
if (length > 0) {
item = array[length - 1];
array.length -= 1;
}
return item;
}
Edit
I'm assuming that the issue with the compiler is that Array.prototype.pop isn't understood at all. Re-reading your post, it looks like arrays have a pop method, but the compiler can't work out whether the variable is an array or not. In that case, an even simpler version of this function would be this:
function pop(array) {
return Array.prototype.pop.call(array);
}
Try that first as it'll be slightly faster and more robust, if it works. It's also the pattern for any other array method that you may need to use.
With this modification, it works:
http://jsfiddle.net/vxxfxvpL/1/
pop2 = function(arr) {
if(arr.length>0){
for(var w=undefined,x=[],y=0,z=arr.length;y<=z;y++){
if(y+1<z) {
(x[y]=arr[y]);
} else {
(w=arr[y],arr=x);
break;
}
}
}
return w;
}
Arr = [-1,0,1,2];
// Testing...
console.log(pop2(Arr)); // 2
The problem now is to remove the last element. You should construct the original array again without last element. You will have problems with this because you can't modify the original array. That's why this tasks are maded with prototype (Array.prototype.pop2 maybe can help you)
This may be really simple, but I've beat my head against the wall trying to figure it out.
I need to grab a value from a JSON response, but the key returned in the response is random, so I can't directly reference it to drill into it.
Here's the response I'm getting back:
var c = {
"success": {
"7d40ab5352b0471cae5bdefc2e032840": {
"__type__" : "user",
"__id__" : "7d40ab5352b0471cae5bdefc2e032840"
}
},
"errors": {}
}
What I need is the random string you see there - the ID. I've tried all kinds of things, and cannot for the life of me figure out how to get the ID back as a string. I've tried getting at it with array notation c.success[0][0] to no avail. Obviously, I can't use dot notation, since I don't know what to put after .success.
Anyone know what to do in a situation where the keys of the array aren't known beforehand? I want to make sure that I do this in a way that's considered the best practice, not a hack.
Thanks...and if I've somehow missed an answer to this that's otherwise published, please send me that way. I've searched for days and can't find this answer.
This:
var obj = c.success[ Object.keys( c.success )[0] ];
obj.__type__ // "user"
obj.__id__ // "7d40ab5352b0471cae5bdefc2e032840"
Live demo: http://jsfiddle.net/AJaBS/
for (var prop in c.success) {
alert(c.success[prop].__id__); // Replace the alert with whatever you want to do with the ID
// break; // Uncomment if there can be more than one ID returned and you only want one
}
and if the key is the same as the __id__ value, you can simply do:
for (var prop in c.success) {
alert(prop); // Replace the alert with whatever you want to do with the ID
// break; // Uncomment if there can be more than one ID returned and you only want one
}
Although Šime Vidas's use of Object.keys is more elegant, you will need the above code to work in older browsers unless you use what is called a him (i.e., you add some extra code which lets you use new standards today--i.e., an implementation of Object.keys which does the same thing as I did above, unless a built-in version already exists, in which case the shim will give preference to the built-in version).
You can use a simple loop:
for (var id in c.success) {
var obj = c.success[id];
// do something
}
If you want to ensure that only the first property in the object will be handled, you can add a break; statement in the end.