push an assoc object into array - javascript

says I've this :
var user = [{'id':1,'gender':'male'},{'id':2,'gender':'female'}]
I want to use push() to insert
'owner':true
into the first array so that it become like this
var user = [{'id':1,'gender':'male','owner':true},{'id':2,'gender':'female'}]
I tried
user[0].push({'owner':true});
but it doesn't work tht way.

#Kim Gysen gave you a solution that works. I think you're getting the logic between Arrays and Objects confused I just wanted to give you a solution using only JavaScript that may help you understand just what's going on here. Using libraries like jQuery are a great way to save time but for you I think it would be helpful to have a more comprehensive understanding.
user[0]['owner'] = true;
In the code above you are accessing your array by the 0th index which in this case is "'id':1" and adding a new property to it using Bracket Notation. Another way to do this would be using Dot Notation:
user[0].owner = true;
Think about the process of adding a property to an object:
var myObj = {};
myObj['newKey'] = "I'm a new value";
myObj['newKey2'] = "I'm an even newer value!";
The reason I gave you an answer is it may seem convenient to use jQuery but understanding JavaScript principles and syntax will help you out in the long run. Some good resources for you I'd suggest are CodeSchool and CodeAcademy

You are not pushing an object into an array, you are pushing an object into an object.
You can do this by using jquery's extend method.
var object = $.extend({}, object1, object2);

Related

map.delete(key) during map.forEach

Typically, you cannot safely delete items from an list while you're looping through that list. Does this concept remain true for ES6 Maps?
I tried this simple test without exceptions:
var map = new Map([['a',1],['b',2],['c',3]]);
map.forEach((value,key,map)=>
{
map.delete(key);
let str = `["${key}",${value}] was deleted. `;
str += `map.size = ${map.size}`;
console.log(str);
});
It seems ok.
Update: I just read this reference from Mozilla. It is certainly doable. I'd be interested in any performance benchmarks comparing this method of deletion with other methods (on larger datasets).
Well I guess you're right. I am not quite familiar with the ES6 Maps, but had done a bit of research and found this blog a bit helpful where it explains about the MAPS:
https://hackernoon.com/what-you-should-know-about-es6-maps-dc66af6b9a1e
Here you will get the deleting mechanism explanation too:
Something like this:
var m = new Map()
m.set('a', 1)
m.set('b', 2)
m.delete('a'); // true
m.delete('c'); // false (key was not there to delete)
Hope this helps.
Why? If you are working with the same instance, actually you can delete. It has functions which are used for deleting an item, so you can delete.
But from the side of Optimization don't delete any item from the Map or array. Javascript engines have optimizations based on the shape of the object. If it is the same over some reference to that object, it would be optimized. Instead of this, create a new object from the filtered values of the current object.
var map = new Map([['a',1],['b',2],['c',3]]);
map.forEach((value,key,map)=>
{
map.delete(key);
});
console.log(map);
There are some languages ( C# ), that you can't remove items from the IEnumerable in the for each loop, because it works another way under the hood, actually it gives you only read and update access, not delete.

When/If to use Delete in Javascript

I just found out that javascript has a delete statement. I've read a bit about it and am not much the wiser.
So I am hoping to get a functional definition of when I should use it, if at all. So I know I can delete properties of an object; as is made obvious by this fiddle:
var myData = {a:"hello",b:"world"};
alert(myData.b);
delete myData.b;
alert(myData.b);
Which shows "world" then undefined in successive alerts. However, you cannot use delete like this (as one might in C++):
function data() {
this.attribute1 = "aww";
this.attribute2 = "poo";
}
var myData = new data();
delete myData;
Here delete returns false indicating that you cannot delete myData. I used to work primarily in C++ and this was like the whole idea of delete. I can't think of any reason I would use delete to remove properties. Should I ever worry about using delete to mark memory to be freed? Like if I do something like this.
var myData = new data();
... //do stuff
myData = new data();
Addition
So I dug up the post that confused me. The most upvoted answer on this question states (as quoted from the Apple Javascript Coding Guidelines):
Use delete statements. Whenever you create an object using a new statement, pair it with a delete statement. This ensures that all of the memory associated with the object, including its property name, is available for garbage collection. The delete statement is discussed more in “Freeing Objects.”
So, if I understand some of the comments and answers I've been given, this statement is not accurate, because you cannot even call delete on an object created using a new statement.
According to mozilla's developer documents, delete does not work that way.
The delete operator deletes a property from an object, it does not delete the object itself.
So instead of using it as you have demonstrated, you would use it more like the following:
myGlobalObject = {};
var myObject = {};
myObject.propertyA = "blah";
// Do some stuff
delete myObject.propertyA; // This works because you're deleting a property off myObject
delete myGlobalObject; // This works because myGlobalObject is a property of the global object.
delete myObject; // This does NOT work - most likely because you declared it using the var keyword
This doesn't actually do garbage collection though. Also if myObject has a prototype up the chain that has propertyA it would still inherit that property through the prototype.
For more indepth information feel free to check out the developer documents:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
delete on its own specifically states:
The delete operator removes a property from an object.
You might remove a property if you don't want it included in data sent to a server, or used by other code, e.g., something that automatically takes object data and turns it into a table.
In general you'd never use it for memory management, a possible exception being if you had a huge chunk of data in an object (like received from the back end) that you explicitly don't need.

Javascript: How do I do array methods on propertied variables i.e. var.hello.push? Too used to AS3

I've been trying to store data for multiple entities, so I thought a good way to organize it like I did in AS3 would be to store it under another variable, like
StoreInventories.Shellys
and then perform array methods on them as needed,
Eg:
StoreInventories.Shellys.push ("Stuff")
But this doesn't seem to work, something about
TypeError: StoreInventories.Shellys.push is not a function
that the console keeps spitting out. How am I supposed to get this functionality?
Sorry if I'm abusing terms - jargon isn't my strong suit and I haven't undergone any formal training.
Method push() is defined for Array class. So you need to create an array first.
Here is the code:
var StoreInventories = {};
StoreInventories.Shellys = [];
StoreInventories.Shellys.push("Stuff");

TypeScript: Accessing JQuery children as array

I'm going through a porting exercise going from JavaScript to TypeScript and have hit the following issue.
In the original JavaScript code I've got:
var children = someJQueryElement.children('div');
var sortedChildren = children.sort(someSortFunction);
In TypeScript (1.4) all the jQuery methods return JQuery which isn't an array and therefore can't have sort called on it.
How should I go about solving this?
As an idea, have you tried to tell TypeScript to treat it as an array using casting?
var children = someJQueryElement.children('div');
var sortedChildren = (<Array>children).sort(someSortFunction);
This seems like a fairly tedious solution, though, if you have to do this in many places. Hopefully someone has a better answer.
You can change to a normal array using .get()
children.get().sort(someSortFunction);
You can use Array.slice.apply to pass in the array-like object and convert it to a proper array.
var children = [].slice.apply(someJQueryElement.children('div'));
This is also a useful practice if you're not using jQuery but want to convert any other array-like objects, like arguments, for example.

Javascript Array Key Retrieval

My JavaScript code stores a lot of data in arrays. I want to retrieve a key using something similar to what I wrote below. It key that should be retrieved is based on variables that are page-dependent . The following code doesn't work. Can anyone give me a solution to this problem?
This is part of a script that does automatic conjugation. (looks for SUBJECT in a div and then looks for VERB in another div and then conjugates the verb by retrieving the conjugated form from the array)
function getarray(Array,Key) {
return Array[Key];
}
Example of how it should work:
verb = innerhtmlfromdiv;
subject = innerhtmlfromotherdiv;
function getarray(Array,Key) {
return Array[Key]; }
conjugatedverb = getarray(verb,subject);
htmltextbox.value = conjugatedverb;
First off, what you want is an Object, not an Array. I'm guessing that you're new to javascript and your previous language was either PHP or PERL, and so you think what you're using is an "Associative Array".
The basics: There is no such thing as Associative arrays in Javascript. There is Objects, and a non-primitive subclass of Object called Array, which has some methods for dealing with Numericly named object properties, and a magic length property.
Since the keys you are dealing with are strings, not numbers, you have no use for Arrays.
Javascript Objects on the other hand are similar to an Associative array in php, or a hash in perl. (but they are not exactly the same thing).
As you have no doubt discovered, with an Object, you can use subscript notation to access certain properties, as in
verbs["go"] = "went";
this is equivilent to
verbs.go = "went";
a common mistake is to think that the dot notation is only used for objects, and the subscript notation for "associative arrays", because this is how it works in PHP. In javascript the two notations are interchangable. Since Arrays are a subclass of Object, the above examples work on them as well (but they don't use any special properties of Arrays).
As for your specific problem:
You need an object full of objects.
so for instance
var verbs = {
"do":{"Truck":"Drive","Blender":"Turn On","Bike":"Ride"},
"take":{"Money":"Steal","Julie":"Accompany","Lever":"Pull}
}
then your function would be:
function conjugate (verb, subject) {
return verbs[verb][subject];
}
and an example of its use would be
conjugate("do","Truck") // returns "Drive"
Try changing the parameter name Array to something else. Array is the name of a built-in function/object in javascript.
I don't quite get the point of the function. This is like writing:
function getValue(var) {return var}
Why not just get the value the normal way without wrapping it in a useless function:
conjugatedverb = verb[subject];
htmltextbox.value = conjugatedverb;
Also, your code doesn't make sense when you claim to do an innerHTML from an element and somehow get an object instead of a string. What is really going on? I think your problem starts even before this snippet of code.

Categories