Can Javascript objects be accessed like arrays? - javascript

Assuming an object is initialized as following:
var myObj = {
"key1":"val1",
"key2":"val2",
"key3":"val3",
...
};
Can I retrieve key values like this?
var retrKey1 = myObj[0];
var retrKey2 = myObj[1];
var retrKey3 = myObj[2];
...
The issue I am trying to solve is that I need to pick random key values from this object. Generating a random number is not an issue, but:
How can I retrieve the number of keys in the object/map?
Can I retrieve the key values using a integer index like in arrays?
If not, what are my options?

The Object.keys method returns an array of object properties. You can index the array with numbers then.
var myObj = {
"key1":"val1",
"key2":"val2",
"key3":"val3",
...
};
var keys = Object.keys(myObj);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

No, because there's no ordering among property keys. If you want ordered keys, you need to work with an array.
You could define a structure like this :
var myObj = [
{key:"key1", val:"val1"},
...
];

Related

how to create array of json object without key in javascript

I want to create an array of JSON object without a key.How can this is achieved ..??
for example [{8,0,2}, {20,0,2}].
var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push({hh,mm,qty})
it gives data like [{hh:9,mm:8,qty:2}]
I want array like [{9,8,2},{9,3,4}]
You example uses a new feature of ECMAScript 6 that is the shorthand syntax for initialising object properties. This line in your example:
data.push({hh,mm,qty});
is equivalent to this verbose one:
data.push({hh: hh, mm: mm, qty: qty});
An object in JavaScript will always have keys and values. There is no way to save just values in a plain object. However, there are two other solutions.
One is using an array:
data.push([hh, mm, qty]);
Note the square brackets substituting the curly ones. This will obviously push an array of three values onto the data array. When retrieving the values, you can just refer to their index, as an array's items will always retain their indices:
var data2 = [hh, mm, qty];
var hh2 = data2[0];
var mm2 = data2[1];
var qty2 = data2[2];
Another way of just "saving the values" is using a set, though the construction of a Set object will still require passing it an array:
data.push(new Set([hh, mm, qty]));
Accessing the data is less straightforward in this case, as the set will typically only let you iterate it. Unlike similar data structures in other languages, a JavaScript set will retain the order of inserted values. It can therefore be safely converted into an array:
var mySet = new Set([hh, mm, qty]);
var data3 = Array.from(mySet);
var hh3 = data3[0];
var mm3 = data3[1];
var qty3 = data3[2];
You can read more about sets here.
You can wrap it over another JSON object with a key I assume you want a JSON object.
Like this { [{8,0,2}, {20,0,2}] } but this with a problem - It is not a valid JSON.
I had a similar problem for one of my scenario. Then I realised
A top level JSON can't exist without a key!
Consider this example, you have another KV pair in JSON and also this array.
{
"somekey" : "somevalue",
[ {8,0,2}, {20,0,2} ]
}
You can fetch "somevalue" with the key "somekey". But how would you access the array? you can't :(
I would suggest you to use a top level key for the JSON and make this array as value of it's. Example:
{
"my array" : [ {8,0,2}, {20,0,2} ]
}
Without a key value pair, the object was not created. That's why its adding a key using the variable name
Look at this error. Its invalid code
var a = [{8,0,2}, {20,0,2}];
console.log(a)
You could push to an array instead of an object
var data = [];
var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push([hh,mm,qty])
console.log(data)
You can't.
Object Literal Property Value Shorthands allow you to create an object where the property names are inferred from the variable names you use to pass the data into.
If you don't have variable names, then there is nothing for the JS engine to use to figure out what the property names should be.
Consider using a function instead.
console.log([time(8,0,2), time(20,0,2)]);
function time (hh, mm, qty) {
return {hh, mm, qty};
}
The result you get at the end makes sense. By doing {hh,mm,qty} you are effectively saying "Use the variable name as the key and its value as the value". It might help us more if you provide an example of how you intend to use the result and access the variables i.e. the shape of the object you want in the end.
That being said, there are a couple alternatives:
Using values as the keys
If you really wanted your object to look similar to {8,0,2} you could use those values as the keys (all keys get converted to strings anyways) so you could do the following:
var example1 = {8:undefined,0:undefined,2:undefined};
var example2 = {8:null,0:null,2:null};
var keys = [];
for(var name in example1) {
keys.push(name);
}
// keys = ["8","0","2"];
var otherKeys = Object.keys(example2);
// otherKeys = ["8","0","2"];
Setting the keys dynamically
var hh = 9;
var mm = 8;
var qty = 2;
var obj = {};
obj[hh] = null;
obj[mm] = null;
obj[qty] = null;
//obj = {9:null,8:null,2:null};
I'm not certain if this solves your problem or answers your question entirely but it might give you some more insight into what is happening and why. The above examples are a common way to create a quick lookup versus a dictionary with would have values in place of null or undefined.

variable values to store a array

how can I variable values to store a array?
Look my code:
var collection =normal,user,student ;
var array = [collection];
alert(array[0]);
In this case, alert would popup a normal,user,student. but i need an array such as array[0] get normal,array[1] get user,array[2] get student like that
how it is possible
Is there any chance to convert such variable into a JS array?
As normal,user,student are values. You can use split() to split the string using , as deliminator then indexes can be used to access elements.
var collection = "normal,user,student";
var array = collection.split(',');
console.log(array[0]);
There are many, many ways to create arrays ... some examples:
// just declare an array directly
var array1 = ["normal", "user", "student"];
console.log(array1[0]);
// use split to create an array out of a string
var collection = "normal,user,student";
var array2 = collection.split(",");
console.log(array2[1]);
// use split and map to create an array by your needs
var collection = " normal, user , student ";
var array3 = collection.split(",").map(function(value) {
return value.trim();
});
console.log(array3[2]);
// push each value to the array
var array4 = [];
array4.push("normal");
array4.push("user");
array4.push("student");
console.log(array4[0]);
// ...
var collection = "normal,user,student";
var jsarray = collection.split(",");
alert(jsarray[0]);
alert(jsarray[1]);
alert(jsarray[2]);
Are you trying to add the existing variables to the array? If so you are just missing your square brackets:
var collection = [normal, user, student];
If you would like the elements to contain the string values, you would do it like this:
var collection = ["normal", "user", "student"];

Dynamically add or update key value on nested javascript array or object

Maybe I'm not putting in the correct search terms, because I can't find what I want, but I'd like to do something like the below in javascript. I believe the issue could be that I'm trying to dynamically create and assign a value to an array in one call which might not be allowed, or maybe my syntax is just wrong (I come from a PHP background).
var array = [];
array[key][] = value;
return array;
I'm looping through an existing array, and every time I come across a key, I want to add its associated value to a new array under that key. If array[key] doesn't exist yet I want it to be created. If it already exists I want a new value to be added to the existing array[key]. I would like the end result to look something like this:
array = [
[key1] = [value1, value2, value3, value4],
[key2] = [value1, value2, value3, value4],
...
]
It doesn't have to be an array. It can be an object.
Demo code as below:
var array = [];
function pushToArray(key, value){
var subArray = array[key];
if( typeof subArray == "undefined"){
subArray = [];
array[key] = subArray;
}
subArray.push(value);
return subArray;
}
pushToArray("key1", "value11");
pushToArray("key1", "value12");
pushToArray("key2", "value21");
pushToArray("key2", "value22");
console.log(array);
You can use Array to do it, but it looks like Map is what you are looking for? The keys can be stored as Map's key, while for map's object, you can store the Array Objects.
Check out this link Javascripy Map Object

JavaScript Two dimensional Array

I am creating javascript two dimensional array
code is :
var field_arr=[];
$(".dr").each(function(index){
Id=$(this).attr("id");
alert(dragId);
topPos=$("#"+ dragId).position().top;
left=$("#"+ dragId).position().left;
parentDiv=$("#"+dragId).parent().attr("id");
parentDiv= parentDiv.split('-');
paId=parentDiv[1];
field_arr[Id]=new Array();
field_arr[Id]['paId']=paId;
field_arr[Id]['top']=topPos;
field_arr[Id]['left']=left;
});
console.log(field_arr);
Output Is:
[undefined, [] left 140 paId "1" top 10
What is problem in It Any help Should be appreciated.
The problem is in the display method of your arrays. The information is there, but both alert and console.log will not show it to you because it is expected that the only interesting properties of arrays are the ones with numeric indexes.
In JavaScript, unlike PHP, objects are used as maps/associative arrays.
First to check that your information is actually there:
$(".dr").each(function(index){
var Id=$(this).attr("id");
console.log(Id, field_arr[Id]['paId'], field_arr[Id]['top'], field_arr[Id]['left']);
});
Now to make make the display methods work you can go about multiple ways, but the best one is to use objects instead:
var field_arr = Object.create(null); // replace with {} if you want to support IE8-
$(".dr").each(function(index){
var id = $(this).attr("id"); // added var to keep variable local
var drag = $("#"+dragId);
field_arr[id] = Object.create(null); // {}
field_arr[id]['paId'] = drag.parent().attr("id").split('-')[1];
field_arr[id]['top'] = drag.position().top;
field_arr[id]['left'] = drag.position().left;
});
console.log(field_arr);
Iterating over properties of objects is quite easy:
for (var id in field_arr) {
console.log(field_arr[id], field_arr[id]['paId'], 'etc');
}
Add a hasOwnProperty check if your object doesn't inherit from null (var obj = {} needs it, unlike var obj = Object.create(null))
you're storing values with a key string and its wrong because you declared your field_arr as a numerical array (well there's no such thing as associative array in javascript i think).
field_arr[Id] = new Array();
field_arr[Id]['paId']=paId; //this is wrong
You need to create an object to store in values as if they are associated with string keys. But literally they are object properties
redeclare it like this
field_arr[Id] = {}; //you create an object
field_arr[Id]['paId'] = paId; //create an object property named paId and store a value
field_arr[Id].paId = paId; //you can also access property paId like this
EDIT:
but to conform to you current code you can access your indexes using strings by accessing it like a property of an object. (Thanks to Tibos)
var field_arr=[];
...
...
field_arr[Id].paId = paId;

add anonymous object to an object

I know to add a named object to an existing JavaScript object you do this:
var json = {};
json.a = {name:"a"};
But how can you add an object to an existing JavaScript object in a similar fashion without assigning it an associative name, so that it could be accessed by a for() statement. Sorry if I'm being a little vague, I don't know a lot about JavaScript objects.
UPDATE:
I want the end result to look like this:
var json = [{name:'a'}{name:'b'}];
What you have there is not strictly a JSON object. You're using JS object literals rather.
You can do this:
var jsObj = {};
// add a 'name' property
jsObj = { name: 'a'};
var anotherObj = { other: "b" };
// will add 'other' proprty to jsObj
$.extend(jsObj, anotherObj);
// jsObj becomes - {name: 'a', other:'b'}
The JSON representation of above will look like:
var jsonString = "{'name': 'a', 'other':'b'}";
// will give you back jsObj.
var jsonObj = JSON.Parse(jsonString); // eval(jsonString) in older browsers
Note that you cannot have property without a name. This is not valid:
// invalid, will throw error
jsObj = { : 'a'};
Try an array that you push an item on to using
myArrayVar.push(value);
or
myArrayVar[myArrayVar.length] = value;
It makes no sense to have a property of an object without a property name. A "for ... in" loop is a loop over that collection of property names, after all. That is,
for (var k in obj)
will set "k" equal to each of the names of properties in "obj" in turn.
You cannot do this, because a JSON object is a collection of string-value pairs. A value can be an array, and you can push your object into that array, without an associative name.
http://www.json.org/
What you are describing is an array of objects.
var j = [{name:'a'},{name:'b'}];
This has the properties you are looking for. You can operate on it like so:
for(var i in j) {
alert(j[i].name);
}

Categories