Declaring Arrays of Objects within another object - javascript

I have recently gotten into javascript (about four days ago), and I'm having troubles acclimating to the syntax a little bit. I'm creating a calender of sorts and I'm trying to get an array of objects (one for each month) to be declared within my "main" object, the calender. I have done copious amounts of googling and browsed all over W3Schools and can't seem to figure it out. So if I have
var calender = {
:
:...functions{},
months: [],
How would I go about getting objects inside of months and declaring their properties (i.e. months[0] would have a name of "January" and its number of days etc)? I am at a conceptual standstill. Do I accomplish this index by index, or can I just literally declare the objects at array creation? From what I grasped so far, it would seem normally I could just say something like var arr = {varName: "name",...(and so on)}, but it seems doing that in the brackets is not allowed, and I'm not sure syntactically where I access the indices. Or maybe I'm just doing this utterly bass ackwards. Any guidance would be greatly appreciated. Thanks

One way; object literals within an array:
var calendar = {
months: [
{
name : "Jan",
days : 31
},
{
name : "Feb",
days : "28ish"
}
]
};
alert( calendar.months[0].days );

Let's get back to basics, this is how you can write literal objects, arrays and objects containing arrays containing objects that contain arrays:
var my_object = {key1: "value1", key2: "value2"};
console.log(my_object.key1);
var my_array = ["value1", "value2"];
console.log(my_array[0]);
var my_compound = {a: [{b: "c", d: [0, 1, 2]},
{b: "e", d: [3, 4, 5]}]};
console.log(my_compound.a[1].d[0]); // => 3
console.log(my_compound["a"][1]["d"][0]); // same thing, perhaps more readable?

Related

Getting a value from the 2 dimensional array in Javascript

In this program I am supposed to create an 2 dimensional array such as ["S1","S2","S3","S4"] AND ["John","Ben","Dan","Jim"] and give the name as output when the specified serial no is given as input. Eg. John will be the output of S1.I was able to create the program using objects but I am unable to do it with arrays. I dont know how to create a 2 dimensional array as well. Kindly help.
Thanks.
Assuming you mean nested arrays and the result you are after is:
[ [ 'S1', 'S2', 'S3', 'S4' ], [ 'John', 'Ben', 'Dan', 'Jim' ] ]
Consider the following:
var mainArray = [];
var arr1 = ["S1","S2","S3","S4"];
var arr2 = ["John","Ben","Dan","Jim"];
mainArray.push(arr1, arr2);
This should give you the result you are after. Please keep in mind that your question is a bit vague and doesn't tell us what you have tried. It sounds like you need some practice with basic JavaScript. I suggest finding tutorials online(which there are more than enough) and working through them.
For future reference, be sure to show what you have tried in your question.

jQuery unique array function applied to an array of objects

I am trying to apply the jQuery $.unique() function to an array of objects. I enjoy using this function with an array of primative variables but apparently it doesn't work with objects, as seen here: http://jsfiddle.net/abs10gxo/
var arr1 = [
"aaa",
"bbb",
"aaa"
];
console.log($.unique(arr1)); // Works as expected.
var arr2 = [
{ "a": "aaa" },
{ "b": "bbb" },
{ "a": "aaa" }
];
console.log($.unique(arr2)); // Doesn't work as expected.
I can't seem to find any literature on jQuery.com in regard to using this function with an array of objects; it only adheres to primative types. Can anyone recommend a solution? Library or custom are both welcome answers. I am familiar with doing this in C++ where you can overload the comparative == sign operator but not sure if that is the best approach since I am using jQuery.

C# Dictionary equivalent in JavaScript

Is there exist any kind of c# dictionary in JavaScript. I've got an app in angularjs that requests data from an MVC Web Api and once it gets, it makes some changes to it. So the data is an array of objects, which is stored in the MVC Web Api as a Dictionary of objects, but I convert it to list before passing it throug network.
If I convert the Dictionary directly to JSon I get something like:
array = [ {Id:"1", {Id:"1", Name:"Kevin Shields"}},
{Id:"2", {Id:"2", Name:"Natasha Romanoff"}}
];
Well the objects are a little more complex, but you've got now an idea. The problem is that this format is even harder to operate with (I've got alphabetical keys or ids). So is there any equivalent to a dictionary? It's quite simple to do thing like:
Object o = dictionary["1"];
So that's it, thank in advance.
You have two options really, although both essentially do the same thing, it may be worth reading a bit more here, which talks about associative arrays (dictionaries), if you wish to tailor the solution:
var dictionary = new Array();
dictionary['key'] = 'value'
Alternatively:
var dict = [];
dict.push({
key: 'key',
value: 'value'
});
Update
Since ES2015 you can use Map():
const dict = new Map();
dict.set('{propertyName}', {propertyValue});
I know this question is a bit older, but in ES2015 there is a new data structure called map that is much more similar to a dictionary that you would use in C#. So now you don't have to fake one as an object, or as an array.
The MDN covers it pretty well. ES2015 Map
Yes, it's called an object. Object have keys and values just like C# dictonaries. Keys are always strings.
In your case the object would look like this:
{
"1": {
"Id": 1,
"Name":" Kevin Shields"
},
"2": {
"Id": 2,
"Name": "Natasha Romanoff"
}
}
The default ASP.net serializer produces ugly JSON. A better alternative would be Json.NET.
My Example:
var dict = new Array();
// add a key named id with value 111
dict.id = 111;
//change value of id
dict.id = "blablabla";
//another way
// add a key named name with value "myName"
dict["name"] = "myName";
//and delete
delete dict.id;
delete dict["name"]
//another way
dict = {
id: 111,
"name": "myName"
};
//And also another way create associate array
var myMap = { key: [ value1, value2 ] };

Accessing associative array inside an object

I have looked everywhere for this but nobody seems to use associative arrays in objects. Here is my object:
var player = {
Level: 1,
Stats: [{Defense : 5}, {Attack: 1}, {Luck: 3}]
};
I need to access the values of Defense, Attack, and Luck, but how?
I have tried this but it hasn't worked:
player.Stats.Defense
player.Stats.Attack
player.Stats.Luck
Any ideas? Thanks!
P.S. Does it make a difference that I am using jQuery?
You've said you're in control of the structure. If so, change it to this:
var player = {
Level: 1,
Stats: {Defense : 5, Attack: 1, Luck: 3}
};
Note that Stats is now an object, not an array. Then you access that information the way you tried to, player.Stats.Defense and so on. There's no reason to make Stats an array of dissimilar objects, that just makes your life difficult.
You've used the term "associative array" which makes me think you have a PHP background. That term isn't commonly used in the JavaScript world, to avoid confusion with arrays. "Object," "map," or "dictionary" are the terms usually used, probably in that order, all referring to objects ({}). Probably nine times out of ten, if you would use an associative array for something in PHP, you'd use an object for it in JavaScript (in addition to using objects for the same sort of thing you use objects for in PHP).
P.S. Does it make a difference that I am using jQuery?
No, this is language-level rather than library-level, but it's a perfectly reasonable question.
(Making this a CW answer because it's basically what all the comments on the question are saying.)
as Stats: [{Defense : 5}, {Attack: 1}, {Luck: 3}] is array of objects, you need to do:
player.Stats[0].Defense
player.Stats[1].Attack
player.Stats[2].Luck
Here player.Stats is an array of objects. So you'll have to use index for accessing those objects.
var player = {
Level: 1,
Stats: [{Defense : 5}, {Attack: 1}, {Luck: 3}]
};
Use these :
player.Stats[0].Defense
player.Stats[1].Attack
player.Stats[2].Luck

How can I order datetime strings in Javascript?

I get from youtube JSON request (after a small parsing of the objects) these strings (which should represents datetime) :
2009-12-16T15:51:57.000Z
2010-11-04T10:01:15.000Z
2010-11-04T14:00:04.000Z
2010-11-04T11:12:36.000Z
2010-11-04T10:24:26.000Z
2010-11-04T12:05:58.000Z
2010-04-30T13:28:08.000Z
2010-11-17T13:57:27.000Z
In fact I need to order these list (descending), for taking the recent video published.
But how can I order those datetime? Is there a native method on JS?
You can just use a default sort method for this because the dates are perfectly formatted to do some sorting (year, month, day, hour, minute, second). This would be much more difficult if that was the other way around. Check out sort for example:
var unsortedArray = [
"2009-12-16T15:51:57.000Z",
"2010-11-04T10:01:15.000Z",
"2010-11-04T14:00:04.000Z",
"2010-11-04T11:12:36.000Z" ];
var sortedArray = unsortedArray.sort();
If you would like to reverse (descending) sorting, add .reverse() to the sorted array.
An easy way to achieve this would be to put all those into an array of strings and sort that array.
var arr = [ "2", "1", "3" ];
arr.sort(); // this gives [ "1", "2", "3" ]
You can read the full doc there :
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/sort
You asked for a descending sort. A quick way is to use reverse.
http://jsfiddle.net/6pLHP/
a = [
"2009-12-16T15:51:57.000Z",
"2010-11-04T10:01:15.000Z",
"2010-11-04T14:00:04.000Z",
"2010-11-04T11:12:36.000Z",
"2010-11-04T10:24:26.000Z",
"2010-11-04T12:05:58.000Z",
"2010-04-30T13:28:08.000Z",
"2010-11-17T13:57:27.000Z"
];
alert(JSON.stringify(a.sort().reverse()));

Categories

Resources