Repeated index is not storing in associated array in Javascript - javascript

I am trying to store the array with the index and its value in associated array, But it is not storing repeated index with different value. When I alert this json value only unique value is displaying .Here is my code :
arr[1]="AAA";
arr[2]="BBB"
arr[3]="CCC"
arr[2]="DDD"
arr[2]="HHH"
var jsonString = JSON.stringify(arr);
alert(jsonString);

First, javascript has no concept of an associatively indexed array. You have either numerically indexed arrays or objects.
Second, if you try to write data to a given index (or property on an object) that is already defined, you WILL overwrite that value. This is common in any programming language.
It sounds like you simply need to rethink your data structure.

JavaScript does not allow repeated keys. When you write a value in a key that is already set, you are overwriting it and not creating a new key.
You may store multiple values in a key by using an inner list, like this:
arr[1]="AAA";
arr[2]=["BBB"];
arr[3]="CCC";
arr[2].push("DDD");
arr[2].push("HHH");
var jsonString = JSON.stringify(arr);
alert(jsonString);
If you want all your keys to behave like that, you can create a function to replicate this behavior:
function pushToKey(arr, key, value) {
var innerArr = arr[key];
if (innerArr) {
innerArr.push(value);
} else {
arr[key] = [value];
};
}
Then always use this function:
var myArr = [];
pushToKey(myArr, 1, "AAA");
pushToKey(myArr, 2, "BBB");
pushToKey(myArr, 3, "CCC");
pushToKey(myArr, 2, "DDD");
pushToKey(myArr, 2, "HHH");
This will make all values inside myArr to be stored as an array.

Related

How to store value pairs in java script?

I need to store the below value pairs like in java script.
(1,1),(1,2),(1,3)(2,1),(2,2),(2,3)
1750 pairs like the above.
I tried using Map but map keys cannot contain duplicates.
Is there any other way i can store these value pairs in java script?
My function using map variable:
function repository()
{
var snakeRepo = new Map();
var xRepo,yRepo,count=0;
for (xRepo = 305;xRepo <=1085;xRepo=xRepo+15)
{
for (yRepo = 55;yRepo <=535;yRepo=yRepo+15)
{
snakeRepo.set(xRepo,yRepo);
//console.log(xRepo+","+yRepo);
count=count+1;
}
}
console.log(snakeRepo);
}
You can have an array inside of an array or objects inside of the array.
Array inside the array
var arrayInArray = [[1,2], [3,4]];
and you can access the values inside the array with:
//where 0 is the index of the values you want
arrayInArray[0]; //returns [1, 2];
Objects inside the array
var objectInArray = [{firstID: 1, secondID: 2},{firstID: 3, secondID: 4}];
and you casn access the values insde with:
where 0 is the index of the object you want
objectInArray[0]; //returns an object {firstID: 1, secondID: 2}
//alternatively, you can access your object's values by adding a dot
objectInArray[0].firstID; // returns 1
To save the date inside the array you can use
arrayInArray.push([1,2]);
objectInArray.push({id1: 1,id2: 2});
I don't know how you want to use it after, but you can store them as object individually ? Then push them in an array if you want :
var pair = {
value1 : 1,
value2 : 2
}
If values are generated in a for loop, it will be easy to use like this.

Named objects and collection of them

not sure how to ask tbh :)
I'm used of PHP's associative arrays so much that I struggle to understand how to create an "named array" of objects.
Example:
I have two arrays, two ints and one boolean. This represents one of my entities. I have multiple entities on which I'm doing some work.
In PHP I would write:
$entitites[$entitity_id]['items'][] = $item;
$entitites[$entitity_id]['items_status'][] = $item_status;
$entitites[$entitity_id]['items_count']++;
and so on..
How do I do this with objects in JS?
var entities = {items:[], items_status: [], items_count: 0};
entities[entity_id].items.push(item)
How does one name his object for later access (via name or in my case, entity_id?)
This code doesnt work for me to this extend that my webpage goes blank without any errors produced :S
I also tried this:
var entities = {};
var entity = {items:[], items_status: [], items_count: 0};
but then I dont know how to always add values to already existing object in entities object and how to call that exact object via name eg. entity_id.
Halp :(
Keep entities as an object. Then you can just go ahead and add each entity_id as a key and an object which has all the details of that entity as the value.
var entities = {};
entities["1234"] = {
"items" : [],
"items_status" : [],
"items_count" : 0
};
There are 2 types involved here: Objects & Arrays.
Arrays are simple and you're probably familiar with them from any other language:
var myArray = []; // this is an empty array
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
// you could also use "var myArray = [1, 2, 3];" instead
alert(myArray[1]); // alerts the value 2
Note: arrays are actually objects, and can have non-index properties as well
You can also use various array functions such as .push(), .pop(), .shift() and so on to mutate the array instead.
Objects share the square brackets notation, but the purpose is different:
var myObject = {}; // this is an empty object
myObject[0] = 1;
myObject[1] = 2;
myObject[2] = 3;
alert(myObject[1]); // alerts the value 2
// but also...
myObject['prop'] = 4;
alert(myObject['prop']); // alerts the value 4
// and
myObject.prop2 = 5;
alert(myObject.prop2); // alerts the value 5
// and lastly
alert(myObject.prop); // alerts the value 4
So while arrays are accessed by index, objects are accessed by property names.
As for your entities, it looks like an array of objects. Lets see how we can do that:
function Entity() {
this.items = [];
this.items_status = [];
this.items_count = 0;
}
var entitites = [];
entities.push(new Entity());
entities[0].items = [1, 2, 3];
entities[0].items_status = ['good', 'good', 'poor'];
entities[0].items_count = 3;
Or you can wrap insertion in a more elegant function:
Entity.prototype.insert(item, status) {
this.items.push(item);
this.items_status.push(status);
this.items_count++;
}
entities[0].insert(4, 'excellent!');
If you want to keep control of the indexes in your JS array you can do so by not using .push() :
var entities = [];
entities[5] = {items:[], items_status:[], items_count:0};
Just replace 5 by your integer entity_id variable, and there you go.
You can use a regular javascript object to create the associative array you're looking for.
Actually it's PHP's implementation that's abit off but all they do is call it different (associative array) to most other language that simply refer to it as an object or hash.
You can use numeric keys in JS and still access them with the [] square brackets.
It works like this:
var my_obj = {};
my_obj[5] = 'any value';
console.log(my_obj); // {5: 'any value'}
JS will not add any redundant undefined to missing indexes either so when looping over the collection you won't loop over undefined.
Also, I can access the object by using the key as a string or as number so you won't have to check if the key is the right type. Taken from the above example:
console.log(my_obj['5']); // 'any value'
console.log(my_obj[5]); // 'any value'
JS Objects are the equivelant of PHP assoc arrays except JS objects are much more flexible than PHP's associative arrays.
The only downside to this is that you can't have duplicate keys.
No two keys may exist that share the same name, in an array if you .push(an_item) it will create a new index making even a duplicate data entry unique but when overwriting a key with a new value only the last value will persist, mind that :)

Arrays with Objects as Key Values in Javascript

I have the following requirement. I have a pair of integers which is to act as keys and another pair of integers which should act as values. That is:
obj[{key1:12,key2:23}]=[2,3];
obj[{key1:12,key2:22}]=[4,3];
obj[{key1:34,key2:12}]=[4,33];
Also finally when the population of this list is over, I would like to sequentially access the elements of the object/array.
Now it is my understanding that for such arrays which take an object as key, they are known as associative arrays and Javascript doesn't support them..
The following will be the operations I will perform on this structure :
Insertion: I will have keys like (2,3) or (2,4) which I would like to insert into the array with a new keyvalue pair such as [1,2],
Lookup : I may have a key pair like (2,3) which is already inserted into this array and I would like to get it back so that I can modify it.
That is something like:
if(obj[{key1:2,key2:3}])
obj[{key1:2,key2:3}]=[2,5];
else
obj[{key1:2,key2:3}]=[2,-1];
Any suggestions as to how I can implement this in Javascript?
EDIT: These are the two things I tried:
First I made it as an array of objects. This approach didn't work because from looking around, I knew that in such cases, Javascript will call the toString method to get the string equivalent of the object which it will then use an index.
Second, I tried to do an object with object keys containing sub-objects. Something along the lines of this answer: Answer. However I am not sure how to get sequential access to all the elements after I am done with the insertion phase.
You're probably not going to like this much, but it'll at least give you a stable key:
obj[JSON.stringify({key1:12,key2:23})]=[2,3];
So, the big problem is that in an object the 'key' (really, the 'property') must be a string, or be able to be stringified. In your examples, {key1:12,key2:23} will always be stringified to [object Object]. So you'll never get a unique key. The only way to get that unique key is to really serialize it, such as by using the JSON.stringify method.
Note that on IE8 I think you have to include a JSON class.
Here is an object oriented way to do it:
// Constructor
function AssociativeArray() {
this.length = 0;
}
// Add or set value
AssociativeArray.prototype.set = function(key, value) {
key = key.key1+'|'+key.key2;
if(!this[key]) {
this.length++;
}
this[key] = value;
};
// Lookup
AssociativeArray.prototype.get = function(key) {
return this[key.key1+'|'+key.key2];
};
AssociativeArray.prototype.toString = function() {
var k, arr = [];
for(k in this) {
if(this.hasOwnProperty(k) && k !== 'length') {
arr.push(this[k]);
}
}
return arr;
};
// Create Associative Array
var arr = new AssociativeArray();
// empty array
console.log(arr.toString(), 'length='+arr.length); // [] length=0
// add value
arr.set({key1:1, key2:2}, [1,1]);
console.log(arr.toString(), 'length='+arr.length); // [[1,1]] length=1
// add value
arr.set({key1:2, key2:1}, [2,2]);
console.log(arr.toString(), 'length='+arr.length); // [[1,1], [2,2]] length=2
// set value
arr.set({key1:2, key2:1}, [3,3]);
console.log(arr.toString(), 'length='+arr.length); // [[1,1], [3,3]] length=2
// lookup and set
if(arr.get({key1:2, key2:3})) {
arr.set({key1:2, key2:3}, [2,5]);
} else {
arr.set({key1:2, key2:3}, [2,-1]);
}
console.log(arr.toString(), 'length='+arr.length); // [[1, 1], [3, 3], [2, -1]] length=3
Fiddle here: http://jsbin.com/ohOwala/3/edit
You could use a bidimensional array
var arr = [];
arr[2] = [];
arr[2][3] = [1, 2];
Or you could use an object and access the pairs using the object properties names
obj = {
_2_3: [1, 2],
_2_1: [4, 1],
_1_2: [3, 2]
};
and access them like this obj["_2_3"] or this obj._2_3
or maybe you could nest em
obj = {
_1: {
_2: [2,1]
}
};
so you could access them like this obj["_1"]["_2"]
or maybe this
obj = {
1: {
2: [2,1]
}
};
But you will be forced to use associatve array notation obj["1"]["2"]
and as far as i know using the associative array like way for accessing objects properties isnt a good practice
I asked where the objects {key1:2,key3:2} came from because if you have control over it you can implement a toString method for those types that will take care of the Object to string conversion so it can be used as a property name.
//define keypair object type
var MyKeyPair = function(key1,key2){
this.key1=key1;
this.key2=key2;
};
//define tostring for this type
// later obj[aKeyPairInstance] will
// invoke the toString method
// if you don't do this then [Object object]
// would be returned for toString
MyKeyPair.prototype.toString=function(){
//since you know there is only going to be key1 and key2
// you could just:
// return this.key1+":"+this.key2;
//Here follows a more general approach but it'll cost
// you more cpu time, if working with very large amounts
// of data use the shorter version.
var ret=[];
for(thing in this){
if(this.hasOwnProperty(thing)){
ret.push(thing);
ret.push(":");
ret.push(this[thing]);
ret.push(",");
}
}
return ret.join("");
};
// make a bunch of keyPair objects
var keys = [
new MyKeyPair(21,33),
new MyKeyPair(22,34),
new MyKeyPair(23,35),
new MyKeyPair(24,36)
];
//create an object and give it properties
// based on the tostring value of the keypairs
var obj={};
for(var i = 0,len=keys.length;i<len;i++){
obj[keys[i]]=[keys[i].key1,keys[i].key2];
};
console.log(obj);//<=this would not log any usefull info in IE
//Use Chrome, Firefox, Opera or any other browser instead

Getting Length of Object in Javascript / jQuery

I am trying to set up an array in jQuery and I then need to do a for loop on it. But it seems that I cant use an associative array for some reason?
var items = new Array();
items['foo'] = 123456;
items['bar'] = 789012;
items['baz'] = 345678;
items['bat'] = 901234;
alert(items.length);
This is just a test, but it return 0?
You can't make associative array in JavaScript like what you want, instead you can use Object.
For example:
var items = {
foo : 123456,
bar : 789012,
baz : 345678,
bat : 901234
}
And to calculate the length you can do:
var getObjectSize = function(obj) {
var len = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) len++;
}
return len;
};
Use: getObjectSize(items); // output: 4
For more see here.
Another one is:
Object.keys(items).length;
But not supported by all browsers.
var items = new Array();
items['foo'] = 123456;
The problem lies in the very first line. You believe that you are adding an item to the array at the index foo, but you are actually adding a property to the items variable with a key foo and value 123456. If you were to type items.foo it would give you back your 123456.
The problem with this approach is that adding a property to an array does not magically increase it's length.
If you want to have non-numeric indexes, you need to use an object instead of an array:
var items = {
foo: 123456,
bar: 789012,
baz: 345678,
bat: 901234
};
Another approach might be to set up two different arrays, which you construct in parallel:
var items = [], items2 = [];
items.push('foo');
items2.push(123456);
// etc.
alert(items2.length);​
The efficiency of this approach depends on how you'll use it. If you're only going to loop through the list of items and do something to each of them, this approach may be more efficient. But if you need to use it like an associative array (items['foo']), then you're better off building an object.
The .length property returns the highest numerical index of the array. Thus, in your case, there is no numerical index and it returns 0. Try
items[98] = "something";
items.length will be 98..! Use the .length property with caution, and if you also want to count the non-numerical indici, loop over the Object (an Array is also an Object) and count its ownProperties.

In Javascript how to compare and store the values dynamically like Key and value object

In javascript arrays i need to check and assign the values in array like key and value pair .
For example :
if i added some values in the array and the second time the same value is retrieving one more time at that time i need to compare my array and i need to increment the previous value instead of storing the value in the array.please suggest me how to achieve this through javascript or jQuery
In sounds like you want something like a hash table. In JavaScript you should use objects for this:
var data = {};
data['key'] = 5;
// later
data['key'] += 10; // data['key'] is now 15
More information about objects in MDC - Working with Objects.
If you want to associate data with an HTML element, then have a look at jQuery's .data() [docs] method (which uses objects too, so in any case you have to learn about them ;))
If I get you right, you want to check if a given value already exists in an Array and if so, you want to increment that value by... "one" I guess ?
var foo = [10, 7, 44, 12, 102, 5],
pos = foo.indexOf(44);
if( pos > -1 ) {
foo[pos]++;
}
This way you can encapsulate the function which counts the numbers of occurrences of the values and the object in which the counts are stored:
var count = function() {
var counts = {};
return function(key) { if (typeof counts[key]=="number") counts[key]++; else counts[key]=1; return counts[key]; };
}();
document.write(count("a")); // 1
document.write(count("b")); // 1
document.write(count("a")); // 2

Categories

Resources