JavaScript syntax issue: [{ }] hierarchy - javascript

I came across the following nested array and am little confused as to why it uses this particular syntax:
var allQuestions = [{
question: "Which company first implemented the JavaScript language?",
choices: ["Microsoft Corp.", " Sun Microsystems Corp.", "Netscape Communications Corp."],
correctAnswer: 2
}];
Full example: http://jsfiddle.net/alxers/v9t4t/
Is it common practice to use
[{...}]
having declared a such a variable?

The definition is an array with an object literal in it. It is not realy a nested array. The
{
question: "Which company first implemented the JavaScript language?",
choices: ["Microsoft Corp.", " Sun Microsystems Corp.", "Netscape Communications Corp."],
correctAnswer: 2
}
is an object literal, which your array contains. In the fiddle you linked to there are several of these defined in the allQuestions array. By doing this it makes it easy to loop over the array of questions and display each in turn.

What's happening there is listing the object inside an array, example:
[{id:1, value:"any"}, {id:2, value:"any any"}]
So here we have declared array with two objects in it. Another so called "traditional" approach would be:
var arr = [];
var obj1 = {id:1, value:"any"};
arr.push(obj1);
...

The allQuestions variable is supposed to be "an array of questions", where each question is an object with properties like question, choices or correctAnswer.
If it was declared just as var allQuestions = {question: ..., choice: ...}, it would be just the one object. Further code which want to know the number of questions allQuestions.length or access e.g. the first question's test as allQuestions[0].question would not work.
Try adding more questions and you will see what the extra brackets are for:
var allQuestions = [
{ question: "1st...", ...},
{ question: "2nd...", ...},
...
];

allQuestions is just an array of objects and yes, it is common practise.

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.

In an ember model, how can you reference dynamic object keys?

In our application currently we are passing an array of objects from the server side into the model, and each element in the array has a key in it. For instance...
[
{name: "dog", sound: "bark", food: "cats"},
{name: "cat", sound: "meow", food: "mouse"}
]
In the model this is defined like so...
animals: hasMany(Animal, {key: 'name', embedded: true })
Then if we want the data for the cat, we use the findBy feature to find the one with the name = "cat" like so...
var animalName = "cat";
model.get('animals').findBy('name', animalName);
This works well, there are lots of potential types of 'animal' objects, and we already know what we're looking for.
However I'm curious for other reasons if we can pass this in as a Map from the server, which becomes a JSON object on the client that looks like this...
animals : { "dog" : {sound: "bark", food: "cat"},
"cat" : {sound: "meow", food: "mouse"}
}
It seems that in order to do this, in the model code we need to define a "has a" relationship for each potential animal type, which is dynamic and we do not want to hard code all the options here. Is there a way to say animals hasMany animals, but there in a map by name, rather then just an array?
I never figured out how to do this with inheritance the way I wanted, so I ended up defining a animals as a basic attribute...
animals: attr(),
Then putting my object in that and accessing the data with
animals.dog.sound
or
var name = "dog";
animals[name].sound
and this works, although we lose some benefits of the model inheritance system. For this application the inheritance wasn't that important.

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 ] };

How to target specific object in JSON file

Here is my JSON file below. Each object in the array belongs to an Id. So the first object would be #one, second object would be for #two. and so on. I can not figure out how to write this in JavaScript. How can I target which array number[1] with object[1] appends to #two for example? Also I need to delete the first line of the object which is the count line? Thank you!
so to get more into details. I was given an assignment, where I have placed pictures in the html and underneath the pictures, each object in the json file(description for the pictures) is supposed to go underneath it. I am new wtih json and ajax :( so the ids #one, #two... were just examples. There would be 6 ids. one for each object.
[
[
{
"count": "80",
"countTxt":"Buyer logins",
"participantsTxt":"Total for all participating member companies:",
"participantCount":"523"
},
{
"count": "233",
"countTxt":"Searches",
"participantsTxt":"Total for all participating member companies:",
"participantCount":"628"
},
{
"count": "533",
"countTxt":"Views of our member pages",
"participantsTxt":"Total for all participating member companies:",
"participantCount":"2,365"
}
],
[
{
"count": "80",
"countTxt":"Total vists",
"participantsTxt":"Total for all participating member companies:",
"participantCount":"412"
},
{
"count": "53",
"countTxt":"Unique visitors",
"participantsTxt":"Total for all participating member companies:",
"participantCount":"731"
},
{
"count": "1:12 min",
"countTxt":"Total time spent on page",
"participantsTxt":"Total for all participating member companies:",
"participantCount":"784.2 mins"
}
]
]
You have an array containing arrays which contain objects. They don't appear to have those IDs in them anywhere, and with names like #one, #two, and such, it's awkward to assign those (you basically have to have a list of names waiting to be assigned).
The work itself is relatively simple once you have that list:
Parse the JSON into an object graph via JSON.parse.
var outerArray = JSON.parse(jsonText);
Create a blank object you can save the named objects to as properties, like a map:
var map = {};
Type in your list of IDs as an array:
// This assumes no more than 99 elements
var ids = [
"#one", "#two", "#three", /*...and so on...*/, "#ninety-nine"
];
Have an index variable that starts with 0.
Loop through the outermost array; you have lots and lots of options for how to do that, I'd probably use forEach:
outerArray.forEach(function(nestedArray) {
// ...more code here
});
Inside that loop, loop through the objects in the nested array:
outerArray.forEach(function(nestedArray) {
nestedArray.forEach(function(object) {
// ...more code here
});
});
Inside the inner loop, add the current object to your map using the next available ID via your index variable:
map[ids[index++]] = object;
If you really want to, remove the count property from the object:
delete object.count;
So putting it all together:
var index = 0;
var outerArray = JSON.parse(jsonText);
var map = {};
var ids = [ // This assumes no more than 99 elements
"#one", "#two", "#three", /*...and so on...*/, "#ninety-nine"
];
outerArray.forEach(function(nestedArray) {
nestedArray.forEach(function(object) {
map[ids[index++]] = object;
delete object.count; // Doesn't matter whether this is before or after the line above
});
});
Notes:
It's going to be really awkward to access those objects with IDs like #one and such, but I assume you have a reason for it. You do map["#one"] and such to get at the objects.
If you don't have to delete the count property, don't bother.
First, you might want to ask yourself if your current way of formatting the data is appropriate. Currently, your data is formatted like this:
var jsonObject =
[
[{},{},{}],
[{},{},{}]
];
Where you have an outermost array, that contains two arrays, and the json data/javascript objects are then stored inside of those arrays. There probably isn't a need for the outermost array, and it would simplify the way you access the data inside of your json object without it. So keep in mind that all the examples you get here on SO are going to refer to the JSON object as you presented it.
// List off all "countTxt" objects to demonstrate how to
// iterate over a json object that contains nested
// arrays containing data. In your example, you have two arrays
// that each contain json data.
for (var i in jsonObject) {
for (var j in jsonObject[i]){
console.log(jsonObject[i][j].countTxt);
}
}
The above loop will print out the following:
/*
Unique visitors
Total time spent on page
Buyer logins
Searches
Views of our member pages
Total vists
Unique visitors
Total time spent on page
*/
Warning: as T.J. Crowder pointed out, using for..in loops to access json data will come back to bite you, so using this type of for..in looping structure (above) isn't recommended in production code, but it serves as a simple demonstration how you use access notation [] to grab values from an array of data objects. To read up on some best practices, you can read T.J. Crowder's in-depth post on the subject here.
If you want to target a specific item in the jsonObject, you do so like this:
// Grab the second object in the data array:
var secondObjectInJsonData = jsonObject[1];
console.log(secondObjectInJsonData);
// secondObjectInJsonData -> [Object, Object, Object]
If you want to grab specific data inside the data array:
// Grab the second object, inside the first array of json data
var countTxtOfSecondObject = jsonObject[0][2].countTxt;
console.log(countTxtOfSecondObject);
// countTxtOfSecondObject --> "Views of our member pages"
To Delete an object, you can use the delete command
var someObject = jsonObject[1][2];
delete someObject.count;
console.log("someObject after 'count' has been deleted: ", someObject);
Here is a JSFiddle to see all this code in action. Just open up the console in Chrome Developer Tools (in the Chrome browser) to see the output of all the console.log() statements.
First of all, You should reformat your data, Try using JSON Editor Online, this shows a tree view of your data. Chrome Extension is available for this, Please check the Chrome web store. It's a really good practice.
I've reformatted your data and made it into something which is more readable. Take a look;
[
{
"count": "80",
"countTxt":"Buyer logins",
"participantsTxt":"Total for all participating member companies:",
"participantCount":"523"
},
{
"count": "233",
"countTxt":"Searches",
"participantsTxt":"Total for all participating member companies:",
"participantCount":"628"
},
{
"count": "533",
"countTxt":"Views of our member pages",
"participantsTxt":"Total for all participating member companies:",
"participantCount":"2,365"
},
{
"count": "80",
"countTxt":"Total vists",
"participantsTxt":"Total for all participating member companies:",
"participantCount":"412"
},
{
"count": "53",
"countTxt":"Unique visitors",
"participantsTxt":"Total for all participating member companies:",
"participantCount":"731"
},
{
"count": "1:12 min",
"countTxt":"Total time spent on page",
"participantsTxt":"Total for all participating member companies:",
"participantCount":"784.2 mins"
}
]
You can access the JSON data using jQuery.getJSON() method and use jQuery.each method to loop through the object. Try this out;
$.getJSON('data.json', function(data) {
$.each(data, function(k) {
console.log(data[k]);
});
});
Check the console (ctrl+shift+j).
Now you can easily access the string. For eg;
console.log('Count: ' + data[k]['count']); //Displays all the count.
Hope you got some idea, You can play around with the JSON object like this and correct me if I'm wrong. Thank You
You can access the properties as below
json[0][0]["count"]
If you want to delete a property use
delete json[0][0]["count"]
Fiddle http://jsfiddle.net/wa99rxgL/

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

Categories

Resources