create dynamic multi-dimenstional associative array using javascript - javascript

Below is my JS code :
var checkedLength = $(ele).parent().parent().find('table').find(':checkbox:checked').length;
if(checkedLength)
{
$(ele).parent().parent().find('table').find(':checkbox:checked').each(function(i) {
$(this).parent().removeClass().addClass('play');
$(this).prop('checked',false);
var agn = $(this).data('agn');
var value = $(this).data('kid');
checkedValues[agn] = {};
// Make bar an array, if it's not defined yet
checkedValues[agn]["bar"] = checkedValues[agn]["bar"] || [];
checkedValues[agn]["bar"].push(value);
});
console.log(checkedValues);
}
From above code am getting output as :
object {agnName => bar[0] = 6}
Desired O/P :
object {agnName => bar[0] = 4,bar[1] = 5 , bar[2]=> 6}
Can anyone guide me how can achieve this array structure ??
Thanks.

You have a test to see if checkedValues[agn] exists and you create it as an empty object if it doesn't. However you then immediately try to push to an array within that object that doesn't exist
Try changing
checkedValues[agn] = {};
checkedValues[agn]['pl'].push = $(this).data('kid');
To
checkedValues[agn] = {pl:[]};/* add property "pl" who's value is empty array*/
/* now the array exists , can push elements into it*/
checkedValues[agn]['pl'].push($(this).data('kid'));
Also note push() syntax you are using is incorrect.....should be push( value )

You want an object, not an array:
checkedValues = {};
checkedValues.foo = {};
checkedValues.foo.bar = 'baz';
// Another way:
checkedValues["keyname"] = "value";
// You can also use variables as keys
var agn = "foo";
checkedValues[agn] = "value";
// Just don't forget to init nested objects
var agn = "foo";
checkedValues[agn] = {};
checkedValues[agn]["bar"] = "value";
// If you need an array inside:
var agn = "foo";
checkedValues[agn] = {};
// Make bar an array, if it's not defined yet
checkedValues[agn]["bar"] = checkedValues[agn]["bar"] || [];
checkedValues[agn]["bar"].push("value");

associative arrays are done as objects in Javascript:
var data = {
agnName: {
pl: [4, 5, 6]
}
}
so you can access data.agnName.pl[0] to return 4 or more dynamically with data['agnName'].pl[0]

To create a mulch-dimensional obj. you have to initialize obj and then you can enter value. like below
var obj = {}
obj[dynamicval1] = {};
obj[dynamicval1][dynamicval2] = {};
obj[dynamicval1][dynamicval2] = {key1:value1,key2:value2};
Hope it works!

Related

How do I create an object from two array indexes?

I am trying to create a javascript object with two array indexes, but it does not seem possible. Why is that? For example:
var arr = ["name","john"];
var obj = {arr[0]:arr[1]}
Computed property names need brackets [myPropName]
var arr = ["name","john"]
var obj = {[arr[0]]:arr[1]}
obj.name // 'john'
You can also do Object.assign,
var arr = ["name","john"];
var obj = {};
var newObj = Object.assign(obj, {[arr[0]]: arr[1]});
console.log(newObj);
If you use arr[0] then js will understand that the property name is arr[0] not "name", so you need [arr[0]] for it to interpret as "name"
var obj = {[arr[0]]:arr[1]}

Can't access array by named key in JavaScript

I need to pass an array of objects to a php page as part of a larger data structure. I am trying to replicate this structure in JavaScript and pass it via json.
The arrays keys in php have been set as names which I require later in the process.
I know JavaScript doesn't use associated arrays and arrays in JavaScript are essentially objects but documentation suggests I should be able to use named keys.
If this is the case I should also be able to use variables as named keys by using a different syntax.
Can someone then please show me what I am doing wrong?
Example 1: numeric keys (works)
var dataTargets = [];
var obj = {
'test': 'test'
};
dataTargets["0"] = obj;
alert(JSON.stringify(dataTargets));
Example 2: named keys (fails)
var dataTargets = [];
var obj = {
'test': 'test'
};
dataTargets["test"] = obj;
alert(JSON.stringify(dataTargets));
//outputs []
Example 3: variable keys (fails)
var dataTargets = [];
var dtname = "test";
var obj = {
'test': 'test'
};
dataTargets[dtname] = obj;
alert(JSON.stringify(dataTargets));
//outputs []
The properties are actually being correctly assigned to each array; the problem is that JSON.stringify ignores all non-index properties of arrays (treating them more like lists and less like objects). If you want to use named keys in your objects, you will have to use plain objects {} rather than arrays []:
var alert = console.log.bind(console) // for demo purposes
// Example 1: numeric keys
var dataTargets = {};
var obj = {'test':'test'};
dataTargets["0"] = obj;
alert(JSON.stringify(dataTargets));
// Example 2: named keys
var dataTargets = {};
var obj = {'test':'test'};
dataTargets["test"] = obj;
alert(JSON.stringify(dataTargets));
// Example 3: variable keys
var dataTargets = {};
var dtname = "test";
var obj = {'test':'test'};
dataTargets[dtname] = obj;
alert(JSON.stringify(dataTargets));
//outputs []
what you did actually like this
example1:
var dataTargets = [];
var obj = {'test':'test'};
dataTargets[0] = obj;
alert(JSON.stringify(dataTargets));
// outputs [{test:test}]
what you need is:
var dataTargets = {};
var obj = {'test':'test'};
dataTargets["test"] = obj;
alert(JSON.stringify(dataTargets));
//{"test":{{test:test}}}
because array need to be access by index. And object can be what you need

How to add another entry at the beginning of this JSON data? [duplicate]

I have a JSON object which is initiated when the page is loaded, like this:
data[foo] = bar;
data[foo2] = bar2;
data[foo3] = bar3;
Is there a way to inject an element before the first foo element, so that when doing a for var i in data, the new element will be looped through before the elements that were added when the object was initiated?
The reason is, I'm displaying some items to the user. When the user adds a new item via javascript, I want this new item to be displayed above all the existing items, however when I add the new item, i.e
data[newItem] = newItem;
Then the JSON object looks like this:
data[foo] = bar;
data[foo2] = bar2;
data[foo3] = bar3;
data[newItem] = newItem;
Instead of how I want, which is:
data[newItem] = newItem;
data[foo] = bar;
data[foo2] = bar2;
data[foo3] = bar3;
Any ideas?
In JS, object properties' order is not guaranteed. Therefore, even if they are ordered in the JSON string, when parsed as a JS object, you will never predict in what order they come up.
Better use arrays instead. You could use the unshift() method to put the item in the first index.
var data = [bar,bar2,bar3];
data.unshift(newItem);
//data = [newItem,bar,bar2,bar3];
As a compliment to Joseph the Dreamer's answer, I have ran some quick checks in firefox & chrome.
Firefox:
var obj = {};
obj.a = 'a';
obj.c = 'c';
obj.b = 'b';
obj['0'] = '0';
for(var i in obj){
console.log(i);
}
//prints:
a
c
b
0
Chrome:
var obj = {};
obj.a = 'a';
obj.c = 'c';
obj.b = 'b';
obj['0'] = '0';
for(var i in obj){
console.log(i);
}
//prints:
0
a
c
b
I've stumbled upon this and achieved it using:
const newObject = Object.assign({first: value}, oldObject)
As mentioned, order is not guaranteed but for me this is good enough. :)
Is there a way to inject an element before the first foo element?
Which comes first in the array:
window.object or window.alert?
Neither, objects don't have an order. If you want an array use an array. Objects are not arrays.
If you want
var ThingsInOrder = [
FirstThing,
SecondThing,
ThirdThing
];
ThingsInOrder.push(ForthThing);
Use an array.
If you want:
var ThingsNeverInOrder = {
Window,
Alert,
Derp,
Herp
};
ThingsNeverInOrder.foo = bar;
Use an object.
Instead of adding new value in the same object, you can create a new object and arrange properties order as you want.
example :
var objj1 = {name:'viru',lastname:'nehra'};
So create a new object with new property which you want on top:
var obj2 = {age: 21}
and the run:
for(var key in objj1){
obj2[key] = objj1[key]
}
obj2 = {age: 21, name: "viru", lastname: "nehra"}
I think you can convert it to string, append your data at the beginning of the string then re-convert the string to json using "eval"

Adding something to the top of a JSON object

I have a JSON object which is initiated when the page is loaded, like this:
data[foo] = bar;
data[foo2] = bar2;
data[foo3] = bar3;
Is there a way to inject an element before the first foo element, so that when doing a for var i in data, the new element will be looped through before the elements that were added when the object was initiated?
The reason is, I'm displaying some items to the user. When the user adds a new item via javascript, I want this new item to be displayed above all the existing items, however when I add the new item, i.e
data[newItem] = newItem;
Then the JSON object looks like this:
data[foo] = bar;
data[foo2] = bar2;
data[foo3] = bar3;
data[newItem] = newItem;
Instead of how I want, which is:
data[newItem] = newItem;
data[foo] = bar;
data[foo2] = bar2;
data[foo3] = bar3;
Any ideas?
In JS, object properties' order is not guaranteed. Therefore, even if they are ordered in the JSON string, when parsed as a JS object, you will never predict in what order they come up.
Better use arrays instead. You could use the unshift() method to put the item in the first index.
var data = [bar,bar2,bar3];
data.unshift(newItem);
//data = [newItem,bar,bar2,bar3];
As a compliment to Joseph the Dreamer's answer, I have ran some quick checks in firefox & chrome.
Firefox:
var obj = {};
obj.a = 'a';
obj.c = 'c';
obj.b = 'b';
obj['0'] = '0';
for(var i in obj){
console.log(i);
}
//prints:
a
c
b
0
Chrome:
var obj = {};
obj.a = 'a';
obj.c = 'c';
obj.b = 'b';
obj['0'] = '0';
for(var i in obj){
console.log(i);
}
//prints:
0
a
c
b
I've stumbled upon this and achieved it using:
const newObject = Object.assign({first: value}, oldObject)
As mentioned, order is not guaranteed but for me this is good enough. :)
Is there a way to inject an element before the first foo element?
Which comes first in the array:
window.object or window.alert?
Neither, objects don't have an order. If you want an array use an array. Objects are not arrays.
If you want
var ThingsInOrder = [
FirstThing,
SecondThing,
ThirdThing
];
ThingsInOrder.push(ForthThing);
Use an array.
If you want:
var ThingsNeverInOrder = {
Window,
Alert,
Derp,
Herp
};
ThingsNeverInOrder.foo = bar;
Use an object.
Instead of adding new value in the same object, you can create a new object and arrange properties order as you want.
example :
var objj1 = {name:'viru',lastname:'nehra'};
So create a new object with new property which you want on top:
var obj2 = {age: 21}
and the run:
for(var key in objj1){
obj2[key] = objj1[key]
}
obj2 = {age: 21, name: "viru", lastname: "nehra"}
I think you can convert it to string, append your data at the beginning of the string then re-convert the string to json using "eval"

What does [] mean in JavaScript?

In the following javascript code there is [] being assigned as the value of a variable, what does it mean?
var openTollDebug = [];
it is an array literal. It is not quite the same as declaring new Array() - the Array object can be overwritten in JavaScript, but the array literal can't. Here's an example to demonstrate
// let's overwrite the Array object
Array = function(id) {
this.id = id;
}
var a = new Array(1);
var b = [];
console.log(a.hasOwnProperty("id")); // true
console.log(b.hasOwnProperty("id")); // false
console.log(a.push); // false, push doesn't exist on a
console.log(b.push); // true, but it does on b
b.push(2);
console.log(b); // outputs [2]
It means an array.
var openTollDebug = [];
declares the openTollDebug variable and initializes it to an empty array. To put elements into the array you could do the following:
var stringArray = ['element1', 'element2', 'element3'];
alert(stringArray[1]); // displays 'element2'
var numberArray = [1, 2, 3, 4];
alert(numberArray[2]); // displays 3
var objectArray = [{ name: 'john' }, { name: 'peter' }, { name: 'tom' }];
alert(objectArray[1].name); // displays 'peter'
It's an empty array, and is equal to
var openTollDebug = new Array();
It is shorthand for empty array. Same as new Array().
Also {} is an empty object. Objects are like hashtables in Js so you can use it as a dictionary.
It creates an empty array.
This is a good way to have a non-null object.
In JavaScript, it is then very easy to add functions and properties to that object. For example:
openTollDebug.title = 'hello world';
openTollDebug.show = function(){alert('Debug');};
As an array, you can add items:
openTollDebug.push('added item');
openTollDebug[3] = 'just add anywhere';
Many languages have constructs for literals. The [] is an Array literal.
var openTollDebug = [];
is the same as
var openTollDebug = new Array();
Just know that using [] preferred for performance reasons.
There are other literals like Object literals
var MyObject = {
name:'default',
age:22,
hobbies:["golf","video games","otherstuff"]
}
Notice the array literal with data. The [] creates an empty array.
Try to use literals due to performance. You dont write
var obj = new Object({name: 'John'})
You just write
var obj = {name: 'John'}
You also dont write
button.onclick = new Function("alert('Clicked!')");
You write
button.onclick = function () { alert('Clicked') }
And here's a link to a nice blog post about it
var b = [] //it is an array literal.

Categories