Perform omit on the original object - javascript

I am very new to underscore js, I am trying to omit a certain property on an Object. What I did was
myObj = _.omit(myObj,name)
console.log(myObj);
Still the myObj seems to have the property name. Although if I do this it seemes to work
newMyObj= _.omit(myObj,name)
console.log (newMyObj)
it seemed to work fine. What am I doing wrong, can someone help? Ok, so myObj looks like this
Angola: "4.134137685",Brunei: "2.532726835",Countries: "2004",Croatia: "1.717672961", keys: Array[11]
I am trying to omit "keys" which again is an array of objects
Thanks

There are these things called "debuggers". If you don't know what they are, then stop everything you're doing and learn about them now. Search Google for "Chrome devtools", for instance. Stop your code (put a breakpoint) at the point before the call to _.omit. In the console, type in myObj to see exactly what it contains, then also name. Or, you could use the 'Scope Variables" section of devtools to check the value of these variables. Now, make a single step (F10). See if or how the variables have changed, or type myObj again into the console to check its value.
In your particular case, you report that the deletion of the property occurs properly when you do
newMyObj= _.omit(myObj,name)
but not with
myObj= _.omit(myObj,name)
In and of itself, that behavior is completely unexplainable. So there's something else going on that you're not telling us about. My guess is that you are doing something like this:
myObj = { keys: [] };
name = "keys";
delete_property();
console.log(myObj.keys); // []
function delete_property(myObj) {
myObj = _.omit (myObj, name);
}
However, this does not do what you might think. The assignment to myObj within the function does nothing; it just reassigns the value of the function argument. It has no effect on the myObj outside the function.
To be sure, we'd need to see more of your actual code, but this is just a regular old debugging problem of the sort you will encounter thousands of times in your programming career, so you're better off learning to solve it yourself.

I interpreted this question to mean you simply want to remove a property from an object using omit(). Note that omit() returns a copy of the object sans the specified property to remove. The method does not alter the object in place.
Given this premise, the code below, which matches what you have, works just fine:
var copy,
obj = {
Angola: "4.134137685",
Brunei: "2.532726835",
Countries: "2004",
Croatia: "1.717672961",
keys: Array[11]
},
check = function (o) {
_.each(o, function (value, key) {
console.log("key: " + key + " value: " + value);
});
};
copy = _.omit(obj, "keys");
check(copy);
obj = _.omit(obj, "keys");
check(obj);
You will get the same result whether you are using a new variable or the existing one.

Related

Getting the nth names of vars in scope

I have a few variables set up like this:
var foo, bar, fizz, buzz, hello, world;
Now I want to find out how to get those names as a collection of some sort. I am trying to get them since I want to push them in an array as a string.
I hope it doesnt require eval or something hacky. Is what I am trying to do possible?
I just need to know how to get the names, I prefer to solve the rest myself.
Edit: About the answer from the linked duplicate, I dont really get what he is doing there as I get everything other than names. Ive read it before.
In my opinion it would be better if you have used javascript object here and put variables in it as properties:
var obj = {foo:'', bar:'', fizz:''};
This way you can access both name of the property and its value:
obj.foo
for(key in obj) {
alert(key + ': ' + obj[key]);
}
You can get list of variables by Object.keys() method, but it returns all variables that object has:
var ar = Object.keys(this);
console.log(ar);

Using JSON to create instances of an object

I'm trying to learn to program. I've gone through a list of tutorials sites online and I'm stuck on a thing that I think is extremely important for me to understand.
My questions:
(This is what I'd like to understand most) In my for...in loop, why is creating new "obj" objects using the "Contacts" constructor working? It seems like I would need a different name each time I loop so that I don't overwrite the object that I've created the pass before. If this is correct, how do I do this if I don't know anything about the number or value of contacts ahead of time? Additionally, why does the title of the any of the objects in the console logs not say obj? Am I confused about what it means to create an instance of an object? Are the names of these instances unimportant?
Why are all of the properties undefined? Should referencing properties from the temporary "i" variable work?
Creating objects from an unknown total of data entries seems really important. Unfortunately, places like Codecademy fall short here. You always manually create new instances of objects with hardcoded names they give you. But what would happen if there were two of the same name?
Thanks so much for any help I may get on this. Don't hold back from telling me anything else silly that I may be doing.
Here is a link to a console screenshot - http://i.imgur.com/TK4dtfV.png
var TestApp = {};
// my data... taken from wherever
TestApp.jsonContacts = {
contact1: {
name: "Ethan",
age: 24
},
contact2: {
name: "Evan",
age: 30
},
contact3: {
name: "Paul",
age: 9000
}
};
// I know this is silly, just let me pretend...
TestApp.jsonStrung = JSON.stringify(TestApp.jsonContacts);
TestApp.globalContactList = [];
// my constructor function to create instances of Contact
TestApp.Contact = function(name, age){
this.name = name;
this.age = age;
TestApp.globalContactList.push(this);
};
// where I'm taking data and creating new Contact objects
TestApp.instantiateObjects = function(){
// I know this is silly, just let me pretend...
var jsonUnstrung = JSON.parse(TestApp.jsonStrung);
// I think I'm looping through the first set of objects sitting in jsonContacts
for (var i in jsonUnstrung) {
var obj = new TestApp.Contact(i.name, i.age);
console.log(obj);
}
console.log(TestApp.globalContactList);
};
TestApp.instantiateObjects();
In my for...in loop, why is creating new "obj" objects using the "Contacts" constructor working?
A variable is just a holding place for a value. It is not the value itself. If you overwrite a variable with a new value, the previous value it held will continue to exist as long as something is holding a reference to it; it's simply that the variable won't be referring to it anymore.
It seems like I would need a different name each time I loop so that I don't overwrite the object that I've created the pass before.
No, you don't. One variable is fine, as long as you do something with the value before you assign the variable to the next value.
If this is correct, how do I do this if I don't know anything about the number or value of contacts ahead of time?
It doesn't matter how many you have.
Additionally, why does the title of the any of the objects in the console logs not say obj?
console.log() prints out the value that is passed to it. It doesn't care (doesn't know) anything about the variable that you pass to it.
Am I confused about what it means to create an instance of an object?
It seems so. Creating an instance of an object allocates some memory to store that object's values. A variable allows you to gain access to that allocated object.
Are the names of these instances unimportant?
Yes, object instances don't have names.
Why are all of the properties undefined?
i holds the property names of the object you are iterating through, so in this case, the strings "contact1", "contact2", "contact3". These strings don't have a name or age property, so your constructor is receiving two undefined values.
Should referencing properties from the temporary "i" variable work?
You need to use i as a property name to access the property values:
var obj = new TestApp.Contact(jsonUnstrung[i].name, jsonUnstrung[i].age);
In general, it's a good idea not to have side-effects like TestApp.globalContactList.push(this); in a constructor. There may be cases where doing so makes sense, but most of the time, removing that line and doing this would be preferable:
for (var i in jsonUnstrung) {
var contact = jsonUnstrung[i];
var obj = new TestApp.Contact(contact.name, contact.age);
console.log(obj);
TestApp.globalContactList.push(obj);
}

Properties of an empty array

I am a novice in nodejs and javascript .I am learning nodejs. I have a doubt here . I came across a node js code , which I was unable to understand :
jumble = {} ;
jumble.debug = false;
jumble.start = function (guid, callback) {
}
I am still wondering , what does jumble.start do when its just an empty array, any help /links would be appreciated Please
There are no arrays here.
jumble = {} ; creates a object and assigns it to jumble
jumble.debug = false creates a property called debug on the object and assigns the value false to it.
jumble.start = function (guid, callback) {} creates a property called start on the object and assigns a function to it.
You could call that function with jumble.start(1,2), but it wouldn't do anything since the function doesn't have anything between { and }.
I don't know node.js but, I know it is similar to javascript.
So, first of all, jumble is an object and not an array, as you think it is.
debug is a property of jumble object which has been assigned the value of false.
start is a function of jumble object which is obviously empty as it does nothing when called by doing jumble.start(3,4).

Odd Javascript alert output

I have an odd problem. I'm trying to use Javascript to fetch me some values from a multidimensional array, and it's giving me some weird output.
Here is my code:
foo = [['3','4'],['5','6']];
for (bar in foo) {
baz = bar[0];
alert(baz);
qux = bar[1];
alert(qux);
}
Here is the output of the above:
// These are all alerts, by the way
0,undefined,1,undefined,$,f,$,c,e,a,c,l,c,l,i,i,n,a,s,l,i,c,o,a,p,g,e,g,e,i,n,c,o,e,r,e,m,f,l,p,i,h,e,r,g
Can somebody tell me what is happening?
Here is a jsFiddle of the problem: http://jsfiddle.net/Jey6w/
Edit:
Here is another jsFiddle, with another layer of "Inception": http://jsfiddle.net/8vyGq/
The output:
// Again, these are all alerts, and * signifies undefined
0**1**$ff$ceaacllcllinnassliicooappgeegeeinncooerremmfllpiiheergg
The JavaScript for ... in loop gives you the names of the object properties, not the values.
Don't use for ... in for real arrays. Use a numeric index or .forEach().
The reason you're getting your output is complicated and uninteresting, since you just shouldn't do that, but here's a start. The property names will be coerced to strings by the for ... in. Thus, on the first iteration, "bar" is the string "0", so ("0")[0] is just "0", and ("0")[1] is undefined because "bar" is a single-character string.
After that, your for ... in loop staggers into some other properties inherited from somewhere; perhaps you're using Prototype or something. The loop then alerts the first two characters of the names of all those other properties.
I could be wrong, but I think it's due to the fact that bar is returning a reference to a property within an object. Changing your selectors to foo[bar][0] works a treat.
foo = [['3','4'],['5','6']];
for (bar in foo) {
alert(foo[bar][0]);
alert(foo[bar][1]);
}​
In cases where your object is simply a multi-dimensional array, I would sway array from using the for in statement, as it can select unwanted properties. I would stick to the good old fashioned for(start, stop, increment)
foo = [['3','4'],['5','6']];
for (i = 0; i < foo.length; i++) {
alert(foo[i][0]);
alert(foo[i][1]);
}​
Update - jQuery
As there has been mention of jQuery's .each method I thought I'd also post an example of how it could be utilised. The jQuery's each method passes 2 optional parameters, indexInArray, and valueOfElement. Additionally, the jQuery documentation also states that
The value can also be accessed through the this keyword, but
Javascript will always wrap the this value as an Object even if it is
a simple string or number value
With this in mind, we could achieve the same results as previous example, using the following jQuery (jsFiddle):
var foo = [['3','4'],['5','6']];
$.each(foo, function() {
// 'this' is the context of the current item within the array
alert(this[0]);
alert(this[1]);
}​)​

How to delete an object in Javascript crossbrowser

var obj = {
destroy: function(){this = null;}
};
obj.destroy();
This works in Chrome, however firefox is throwing an error referencing this for some reason. Is there a better way to kill this object within a method?
Error:
invalid assignment left-hand side
[Break On This Error] destroy: function(){this = null;}
Not sure why Chrome allows for it but you can't assign a value to this. You can reference this, but you can't assign a value to it.
If you have some array destruction you want to perform you can reference this.myArrayName within your destroy method and free up whatever you're trying to release, but you can't just assign null to this to destroy an instance.
I suppose you could try something like this:
var foo = {
// will nullify all properties/methods of foo on dispose
dispose: function () { for (var key in this) this[key] = null; }
}
foo.dispose();
Pretty much as close as you can get to legally nullifying "this"...
Happy coding.
B
Call me old fashion, but:
foo = null;
I'm not sure why you're making this difficult. Javascript is a garbage collected language. All you have to do to allow something to be freed is to make sure there are no more references to it anywhere.
So, if you start with:
var obj = {
data: "foo";
};
and now you want to get rid or "free" that object, all you have to do is clear the reference to it with:
obj = null;
Since there are no longer any references in your code to that data structure that you originally defined and assigned to obj, the garbage collector will free it.
An object cannot destroy itself (because other things may have references to it). You allow it to be freed by removing all references to it. An object can clear out it's own references to other things, though that is generally not required as removing all references to the object itself will also take care of the references it holds (with the exception of some bugs with circular references between JS and the DOM in certain older browsers - particular IE).
One time when you might explicitly "delete" something is if you have a property on an object that you wish to remove. So, if you have:
var obj = {
data: "foo",
count: 4
};
And you wish to remove the "data" property, you can do that with this:
delete obj.data;
of if the property/key was assigned programmatically via a variable like this:
var key = "xxx";
obj[key] = "foo";
you can remove that key with:
delete obj[key];

Categories

Resources