I have an associative array stored in another associative array. I know how to splice a specific value in just a regular array as such:
arr.splice(arr.indexOf('specific'), 1);
I was wondering how one could splice an array such as this:
arr['hello']['world']
EDIT Would this shorten hello['world']['continent']
var hello = {};
hello['world'] = {};
hello['world']['continent'] = "country";
delete hello['world']['continent'];
alert(hello['world']['continent'])
You should be able to just just use the delete keyword.
delete arr["hello"]["world"]
How do I remove objects from a javascript associative array?
Edit, based on other comments:
For the sake of readability, you can also do:
delete arr.hello.world
Since we are really just talking about objects, and not traditional arrays, there is no array length. You can however delete a key from an object.
JavaScript does not have associative arrays.
Use objects:
var x = {
a : 1,
b : 2,
c : {
a : []
}
}
delete x.c.a;
An "associative array" in javascript isn't actually an array, it's just an object that has properties set on it. Foo["Bar"] is the same thing as Foo.Bar. So you can't really talk about slicing or length here.
Related
In my code i initialize array then put a value inside it why the output be 0 ?in spite of this should be 1
var changedfields=[];
changedfields['product']="productname";
alert(changedfields.length);
You're creating an associative array (normal arrays have an numeric index) but are actually trying to build a HashMap (a key, value pair). Use Objects or ES6 Maps.
I hope the following example will help you out:
var changedfields = {}; // create an object
changedfields['product']="productname";
var keys = Object.keys(changedfields); // returns the keys of the object ['product']
alert(keys.length);
I would suggest to read more about datastructures in javascript and avoid associative arrays in general.
Length of a JavaScript object (that is, associative array)
associative array versus object in javascript
Your question is interesting. Following is the answer.
First of all Arrays in Javascript are object type.
The first line you wrote creates an empty array and it's type is object.
var changedfields=[];
The second line you wrote creates a property called product of changedfields and sets the value to productname. It allows you add the product property because Javascript Array type is object. If you just had var changedfields; you could not add this property.
changedfields['product']="productname";
The third line you wrote simply finds the length of the empty array.
alert(changedfields.length);
In Javascript associative arrays are achieved using object. But if you want to add the product name in changedfields array. You could use push method like below and check the length:
changedfields.push('productname');
console.log(changedfields.length);
Javascript numerical indexed array length
So the Javascript numerical indexed array length can be calculated this way:
console.log(array.length);
console.log(changedfields.length); // in your case
The Javascript associative array length
The Javascript associative array (object) length can be calculated following ways:
Option 1:
Object.len = function(obj) {
var objLen = 0;
for (i in obj) {
obj.hasOwnProperty(i) ? objLen++ : '';
}
return objLen;
};
console.log(Object.len(changedfields));
Option 2:
console.log(Object.keys(array).length);
console.log(Object.keys(changedfields).length); // in your case
Note: This has issues with Internet Explorer 8, Opera etc
This seems to be a common source of confusion from what I've seen, and apparently I'm no exception. I've read a few tutorials on this, and I still can't quite get my head around it. From what I can gather, Arrays are objects in Javascript, just like Strings and other variable types. But I still don't get how that helps me declare a multidimensional array with alphanumeric keys.
In PHP I can simply write:
$calendar = array();
foreach ($schedule->currentExhibitions as $key) {
$calendar[$key["ExhibitionID"]]["startDate"] = date("Y,n,j", strtotime($exhibition["StartDate"]));
$calendar[$key["ExhibitionID"]]["endDate"] = date("Y,n,j", strtotime($exhibition["StartDate"]));
}
But in Javascript trying something similar will create errors. Should I create an Array and fill it will Objects? If so, how would I go about doing so? Or should I just use an Object entirely and skip having any sort of Array? (If so, how do I create a multidimensional Object?)
Sorry for the newbish quesion!
If your keys are strictly numerical and ordered starting at zero, then an array makes sense and you can use square bracket notation just like you would in php, although you will need to initialize sub-arrays if you want to have multiple dimensions :
var myArray = [];
myArray[0] = [];
myArray[0][0] = "something interesting";
If your keys are not numerical, ordered and starting at zero, then you should use an object (all keys are strings), which still allows the square bracket notation :
var myObject = {};
myObject["1A"] = {};
myObject["1A"]["3B"] = "something interesting";
In Javascript, an array is an object, who's keys are numerical, sequential, indexes.
As soon as you want to use alpha-numerica (aka strings) keys, you use a regular object.
In JS to do what you want, you'd do the following (using more or less your php code).
var calendar = {};
Object.keys(schedule.currentExhibitions).forEach(function(key) {
var ex = schedule.currentExhibitions[key];
calendar[ex.exhibitionId] = calendar[ex.exhibitionId] || {}; //if the key doesn't exist, create it.
calendar[ex.exhibitionId].startDate = date(); //some js date function here
calendar[ex.exhibitionId].endDate = date(); //your js date function here
});
I look at Multidimension as nesting, and at multiple levels of nestings as complex objects. For example:
var parent = [];//top holder
var child1 = {};
child1.name = "Jim";
parent.push(child1);
In this simple example, you can access child1 like this:
parent[0]["name"] //Jim
So that is, in a way, multidemensional. Instead of using ["name"] as an indexer, or child1 as an object it could also be an array, like this:
var parent = [];//top holder
var child1 = [];
child1.push("Jim");
parent.push(child1);
In this example, you could get Jim with:
parent[0][0];//Jim
So for complex examples you may have multiple levels of these nestings (or dimensions).
parent[0]["Child"].grandChild[5]["cousin"].name //etc
Where that would just be a continuation of the previous examples down the line.
If you want to preserve order or you want to access by numeric index, use an array. The value of the array can be a single value or an object or array itself (so each value in the array can contain more than a simple value).
If you want to access by a unique alphanumeric key, then use an object and assign properties to it.
Arrays have numeric indexes. They do not have alphanumeric indexes.
Objects have string keys.
Because an array is also an object, it can have both types of keys, but using a string key is not an array access, it's accessing a property of the object.
When you ask for the .length of an array, you only get the length of the numeric indexes. It does not include other properties of the object.
An array of objects is a very practical data structure in javascript and is used quite often when either order or index by numeric index is important.
If order is not important or you don't need to access by numeric index and just want to access by an alpha numeric string, then you should just use an object and set a properties on it with keys that are your alphanumeric string.
I'm parsing JSON and getting an array of objects with javascript. I've been doing this to then append an element for each object:
for(o in obj){ ... }
But I realized that for a certain situation I want to go backwards through the array. So I tried this before the for loop:
obj = obj.reverse();
However this isn't reversing the order of the objects in the array. I could simply put a count variable in the for loop to manually get the reverse, but I'm puzzled as to why reverse doesn't seem to work with object arrays.
There's no such thing as an "object array" in JavaScript. There are Objects, and there are Arrays (which, of course, are also Objects). Objects have properties and the properties are not ordered in any defined way.
In other words, if you've got:
var obj = { a: 1, b: 2, c: 3 };
there's no guarantee that a for ... in loop will visit the properties in the order "a", "b", "c".
Now, if you've got an array of objects like:
var arr = [ { a: 1 }, { b: 2 }, { c: 3 } ];
then that's an ordinary array, and you can reverse it. The .reverse() method mutates the array, so you don't re-assign it. If you do have an array of objects (or a real array of any sort of values), then you should not use for ... in to iterate through it. Use a numeric index.
edit — it's pointed out in a helpful comment that .reverse() does return a reference to the array, so reassigning won't hurt anything.
That's because the for (o in obj) doesn't iterate the array as an array, but as an object. It iterates the properties in the object, which also includes the members in the array, but they are iterated in order of name, not the order that you placed them in the array.
Besides, you are using the reverse method wrong. It reverses the array in place, so don't use the return value:
obj.reverse();
It seems it's always empty :
var idStruttura=2;
var arrayMarkers=new Array();
arrayMarkers["sede_"+idStruttura] = "ciao";
alert(arrayMarkers.length);
Prints always 0. Why? And how can I fix it?
An array is not an associative array, however the array object is an object, and all objects are associative arrays. If you use a string as key when assigning items to the array, you are not using it as an array, you are using it as an object.
The length property of the array returns how many items you have stored in the array. If you also use the array object as an associative array, that won't affect how you use the array as an array.
What you've created is a regular array object and added a property to it called sede_.... JavaScript doesn't use associative arrays in the same way a language like PHP does. Arrays are objects that can have properties, but those properties are not among the numerically indexed array elements.
var idStruttura=2;
var arrayMarkers=new Array();
// Push an object onto the array having one property:
arrayMarkers.push({"sede_" + idStruttura : "ciao"});
// Or declare it as an object to begin with:
// This makes more sense....
var objMarkers = {};
objMarkers['sede_' + id] = 'ciao';
There is no length when you store objects, only when you use the array as intended.
Try this (DEMO)
var idStruttura=2;
var arrayMarkers={}; // creates a more appropriate object than []
arrayMarkers["sede_"+idStruttura] = "ciao";
arrayMarkers["sede_"+(++idStruttura)] = "espresso";
var len = 0;
for (var o in arrayMarkers) {
if (arrayMarkers.hasOwnProperty(o)) len++;
}
arrayMarkers.length=len
alert(arrayMarkers.length)
array's in javascript (unlike php) cannot have string key's, only numeric keys. If you want a string literal as a key, please use objects
What you need is a simple Object, not an Array. Arrays have numeric indexes.
var markers = {};
markers['sede_' + id] = 'ciao';
Also note that {} is the same as new Object() and [] is the same as new Array(). Always use the former ones. It's much clear to any JS developer.
I have to push elements in an associative array from another array after some processing and I'm doing something this:
for(var i in this.aNames) {
var a = this.aNames[i];
// some processing on a
aList[i] = a;
aList.push(i);
}
But it's not giving me the proper array.
EDIT :
Here aNames is an associative array like this
'1232':'asdasdasd',
'6578':'dasdasdas'
...... and so on of about 100 elements.
I'm using for here as I want to do some changes in every element of the array.
Then I'm displaying the result array on the page but it's showing the key value together with the array data.
I.e. it should only display asdasdasd or asdasdasd but it's displaying keys too, like 1232 asdasdasd 6578 dasdasdas.
There are multiple things which may go wrong...
Primarily, make sure that this is pointing to the correct context and that this.aNames is actually returning a complex object (associative array).
Also, what's aList? Is it an array? If it is, push should append your array with the key of the current member (the member's name).
If you want to append the values of the members on your source object, you need to do something like this:
var obj = {name: 'dreas'},
arr = []; // arr is an array
arr.push(obj["name"]); // arr now contains a single element, 'dreas'
In your for..in construct, you are both adding elements to an alleged array (aList) with push but also creating new members on your array (with the subscript notation, aList[i] = "asd" since i in this case (for..in iteration) refers to the member's name).
So, what you need to do is decide if you want to add elements to an array or members to an object, not both.
If you just want to clone an array, use a for loop. If on the other hand you want to clone an object, it's not that trivial because members can also be complex objects containing their own members, and simply doing arr[i] = obj.member will only copy a pointer to arr[i] if member is a complext object, not a value type.
Just to make sure my terminology is understandable:
var anObject = {name: "dreas"},
anArray = [1,2,3];
anObject["name"] <= member (results in "dreas")
anArray[1] <= element (results in 2)