Pushing key-value pairs and using them without indices - javascript

Can I somehow push the key:vale pairs to a JavaScript array so that I can later use them without indices even if I don't know what order I'll grab them in? I mean, such code would work:
var test = [];
test.push({key1: 5});
test.push({key2: 7});
console.log(test[0].key1);
But let's say I don't always receive the keys in that order and would like the last line to just be console.log(test.key1);, without the need to index it. Can I somehow push the pairs in such a way that later I only need to specify the key for which I want a value, and not an index under which it resides?

Yes...
var test = {};
test.key1 = 5;
test.key2 = 7;

instead of push, use an object and assing key1 to that like this: test.key1 = 5
but now it can't work as array

Related

How can I dynamically reference a variable key name in a Javascript object?

I have an array with the name data containing objects like so:
[{"timeslot":"6am-7am","Monday":5},{"timeslot":"7am-8am","Monday":0},{"timeslot":"8am-9am","Monday":10}]
Each object contains two key-value pairs. I need to create two new arrays:
an array, timeslots, containing each value associated with the "timeslot" key
an array, numUsers, containing each integer value associated with the "Monday" key
Here is my Javascript:
var timeslots = [];
var numUsers = [];
var keys = Object.keys(data[0]);
var today = keys[1];
for(var i in data) {
timeslots.push(data[i].timeslot);
numUsers.push(data[i].today);
}
The first line of the for loop works, and returns the following timeslots array:
["6am-7am", "7am-8am", "8am-9am"]
The second line, however, returns an array of undefined elements.
My problem is, the second key value of the objects in the data array varies. Each object will contain the same day of the week, but this day can be any one of "Monday" through "Sunday".
How can I reference it dynamically?
You can access object value using square brackets notation in the same way as you use it with i:
numUsers.push(data[i][today]);
N.B. However, your code has several very important problems that will eventually bring you errors. One of the most visible is that you rely on the order of the object properties and retrieve an array of keys with Object.keys, setting the second key as the value of today variable. Your mistake is that in different systems and browsers the code like Object.keys(obj)[1] may return different results, as object properties in JavaScript don't have order. Also, you shouldn't use for .. in statement to iterate arrays, instead utilise simple for (var i = 0, len = arr.length; i < len; i++) loop. And finally, don't forget, that data array may contain zero items, so your code data[0] will raise an error. I would suggest you to reconsider the business logic of your application and probably to rewrite it to make it more reliable.
You need this:
numUsers.push(data[i][Object.keys(data[i])[1]]);

Retrieve a key value from JSON

I've got a Calendar. Inside its code there's an Object and a JSON to it, which contains several properties such as
[{"Date":"17-3-2015","Event":"Test drive","Participants":"John, George","Description":"Testing a new F30"},
{"Date":"17-3-2015","Event":"Football match","Participants":"FCSM vs FCKK","Description":"New season start"},
{"Date":"25-3-2015","Event":"Jane's Birthday","Participants":"Jane, John, Richard, Alice","Description":"Celebration with my friends"}]
But since that data is in localStorage I retrieved it via
var existEvents = JSON.parse(localStorage.getItem('events'));
for(i=0; i<existEvents.length; i++) {
var item = localStorage.getItem(localStorage.key(i));
console.log(item);
};
existEvents = every new event in my Calendar
console.log(item); returns me the data typed above.
What I need is to retrieve every Date value (= key). So I pretend that
item.Date
must work, but it doesn't. As well as
item[0].value
I tried it after having read this question + answers
Access / process (nested) objects, arrays or JSON
What am I doing wrong? Please, help!
A good way to use the Array.ForEach(), where it can be also used to loop on objects having the value as the first parameter and the key (if exists) in the second. In your example the for each takes this array, and loops on it retrieving one object at a time.
This object has a Date key in it, so you can access it using the obj.key. However, it is always good to use the .hasOwnProperty to check if the key exists first.
You can also use the forEach to loop through the object keys and then you will be able to have the obj/key. For example, looping on every obj from the array loop will give you obj => 17-3-2015 | key => Date ... etc.
var x = [{"Date":"17-3-2015","Event":"Test drive","Participants":"John, George","Description":"Testing a new F30"},
{"Date":"17-3-2015","Event":"Football match","Participants":"FCSM vs FCKK","Description":"New season start"},
{"Date":"25-3-2015","Event":"Jane's Birthday","Participants":"Jane, John, Richard, Alice","Description":"Celebration with my friends"}];
x.forEach(function(obj,key){console.log(obj.Date) });
Your code can be:
JSON.parse(localStorage.getItem('events')).forEach(function(obj,key){console.log(obj.Date) });
I don't think you need to be going back into localstorage inside your for loop since you already have all of your data in the variable existEvents.
var existEvents = JSON.parse(localStorage.getItem('events'));
for(i=0; i<existEvents.length; i++) {
var item = existEvents[i];
console.log(item);
};
The HTML5 LocalStorage is an associative array storage with the getItem function grabbing one of the items. So,
localStorage.getItem ("somekey")
returns whatever variable somekey was set to. In your code snippet, the variable you are storing in the localStorage is a String that happens to be in JSON form. JSON.parse () turns that JSON into the actual array represented by the String you've stored.
var existEvents = JSON.parse (localStorage.getItem ('events'));
for (var i = 0; i < existEvents.length; i++) {
var item = existEvents [i];
console.log(item);
};
existEvents is an Array object so you can access it like normal. After you've retrieved it from localStorage and parsed it, you no longer need to access localStorage.getItem.

Pulling an integer out of an object and assigning it to a variable

If I have an object that contains a number, like this:objNum = {Num:"12345"} and I want to put the contents of Num into an array, how would I go about that. I have tried using objNum.Num, like this: intAr = objNum.Numbut when I try to call the index of the array at that point, I only get the first number, or 1. What is the correct way to do this?
You actually have to declare the array, then push the value to it:
var intAr = [];
intAr.push(objNum.Num);
Or
var intAr = [objNum.Num]

Trouble with basic Javascript

I haven't touched Javascript in a while and now I'm having trouble with basic arrays.
params=new Array();
params['return']='json';
alert(params.length);
This always returns 0 when I'm expecting 1. What's wrong with this?
Arrays use numerical indexes. When you use a string "index", it just adds a new property to the array object, but the new value isn't in the array.
Thus, the array is still empty, but you can access your value as you could with any other object.
Your code is equivalent to
var params = {}; //new object (not array)
params['return']='json'; //new property added to object
A few things:
You forgot var:
var params = new Array();
But an array takes numeric indices, so params['return'] is not really a member of the array but of the object that represents the array, so it doesn't affect the length.
You could use an object but objects have no length:
var params = {};
params['return'] = 'json';
To get the length though you can count the keys in that object and get the length of the resulting array:
var len = Object.keys(params).length;
Javascript arrays don't hold key value pairs like objects do, so the length isn't incremented when you assign a value. They are however objects themselves, so you can assign values to its properties (in this case the return property).
You probably want params to be a plain object: params = {}
You need to count the properties, like this for example:
function dictionarySize(dict){
var size = 0;
for (key in dict){
// In practice you'd probably want to filter using hasOwnProperty
size++;
}
return size
}
alert(dictionarySize(params));
Or using a library like underscore.js:
_.size(params);
Object.keys is also an option, although it won't work in IE8 and older.
If you don't need an key value pairs use params.push:
params=new Array();
params.push('json')
alert(params.length); // 1
You can create an array, push stuff on it, and assign properties to values of it like so:
var params=[];
params.push('firstly');
params[0]="jonson";
params['return']="fredy"
params.newone="json";
params.push('Carl');
NOW, if you do:
console.log(params.length,params);
the result of that is:
2 ["jonson", "Carl", return: "fredy", newone: "json"]
SO, you see "firstly" was replaced by "jonson" in the [0] - so the "pushed" value is addresed by the numerical [0]

Javascript array best practice to use [] instead of new array?

I read at many tutorials that the current best practices to create a new javascript array is to use
var arr = []
instead of
var arr = new Array()
What's the reasoning behind that?
It might be because the Array object can be overwritten in JavaScript but the array literal notation cannot. See this answer for an example
Also note that doing:
var x = [5];
Is different than doing:
var x = new Array(5);
The former creates an initializes an array with one element with value of 5. The later creates an initializes an array with 5 undefined elements.
It's less typing, which in my book always wins :-)
Once I fixed a weird bug on one of our pages. The page wanted to create a list of numeric database keys as a Javascript array. The keys were always large integers (a high bit was always set as an indicator). The original code looked like:
var ids = new Array(${the.list});
Well, guess what happened when the list had only one value in it?
var ids = new Array(200010123);
which means, "create an array and initialize it so that there are 200 million empty entries".
Usually an array literal(var a=[1,2,3] or a=[]) is the way to go.
But once in a while you need an array where the length itself is the defining feature of the array.
var A=Array(n) would (using a literal) need two expressions-
var A=[]; A.length=n;
In any event, you do not need the 'new' operator with the Array constructor,
not in the way that you DO need 'new' with a new Date object, say.
To create Array without Length
var arr = [];
To create Array with Length more dynamically
var arr;
( arr = [] ).length = 10; // 10 is array length
To create Array with Length less dynamically
var arr = [];
arr.length = 10;

Categories