accessing nested properties based on structure - javascript

Could anyone please give me an alternate syntax to the following
var id = '-JLxSeCPUCVN13FxifTY';
var ResultsContainer = results[id];
var i=0;
for(var k in ResultsContainer)
{
var TheArrayOfObjectsThatIneed = ResultsContainer[Object.keys(ResultsContainer)[i]];
console.log(TheArrayOfObjectsThatIneed);
//loop the TheArrayOfObjectsThatIneed do the processing
i++;
}
as you see in the image i have an array within an object within an object and i have no idea what the property names are but the structure is always the same {results:{id:{idthatidontknow:[{}]}}} and all i need is to access the arrays
the above code is working nicely but i am new to javescript and i was wondering if there is a nicer syntax and if i am doing it the right way

Perhaps something like this?
var id = '-JLxSeCPUCVN13FxifTY';
var ResultsContainer = results[id];
for(var k in ResultsContainer) {
if (ResultsContainer.hasOwnProperty(k)) {
var TheArrayOfObjectsThatIneed = ResultsContainer[k];
console.log(TheArrayOfObjectsThatIneed);
//loop the TheArrayOfObjectsThatIneed do the processing
}
}

Related

Putting an object into an array in JavaScript

I'm currently working with an MVC JS framework and I want to be able to get a list of objects that I can take a random entry out of on a loop. So far I've managed to create a function that finds a random ID and pulls out that object so that part is not a problem. It's what is going into the array of objects:
QuestionsSetup: function(gameType) {
// Setup Resources
var c = this.View.children;
var player1qs = [];
var leftQ = 0;
var rightQ = 0;
var maxQValue = 50;
var minQValue = 1;
// Fill array with questions
for (var i = 0; i < 5; i++) {
// Build a random question with numbers between 1 and 50
// Build Question Text to output to user
// Generate correct answers based on generated question
// Generate unsorted, incorrect answers and add them to an array
//Place Questions into object
questions.qId = i;
questions.leftQ = leftQ;
questions.rightQ = rightQ;
questions.correctAnswer = correctAnswer;
questions.allAnswers = sortedAnswers;
questions.questionText = questionText;
//Add to array of questions
player1qs.push(questions);
}
}
This does add them to an array but when adding a new object it also changes the values of the existing objects in the array so they all come out the same no matter which one I pull out later. The questions object is declared in it's own file in a models folder. Is there any way, at the start of each loop, to tell the application I want new empty questions object as opposed to referencing the existing ones? I know that you can in similar back end languguages so I refuse to beleive that something so simple doesn't exist in JavaScript too?
Declaring a variable for each array item is definitely missing.
QuestionsSetup: function(gameType) {
// Setup Resources
var c = this.View.children;
var player1qs = [];
var leftQ = 0;
var rightQ = 0;
var maxQValue = 50;
var minQValue = 1;
// Fill array with questions
for (var i = 0; i < 5; i++) {
var tempQuestion = {
qId: i,
leftQ: leftQ,
rightQ: rightQ,
correctAnswer: correctAnswer,
allAnswers: sortedAnswers,
questionText: questionText
}
// ...
//Add to array of questions
player1qs.push(tempQuestion);
}
}
Using a separate closure inside a loop also might be a good idea.
do this:
for (var i = 0; i < 5; i++) {
let questions = {};
// the rest....
you need to define the object first.
Maybe you should just initialize the questions object before initializing its properties, so the code should look like this:
//Place Questions into object
questions = {};
questions.qId = i;
questions.leftQ = leftQ;
questions.rightQ = rightQ;
questions.correctAnswer = correctAnswer;
questions.allAnswers = sortedAnswers;
questions.questionText = questionText;
//Add to array of questions
player1qs.push(questions);

Create variables based on array

I have the following array and a loop fetching the keys (https://jsfiddle.net/ytm04L53/)
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
alert(feed.match(/\d+$/));
}
The array will always contain different number of keys, What I would like to do is either use these keys as variables and assign the value after the : semicolon as its value or just create a new set of variables and assign the values found on these keys to them.
How can I achieve this? so that I can then perform some sort of comparison
if (test_user > 5000) {dosomething}
update
Thanks for the answers, how can I also create a set of variables and assign the array values to them? For instance something like the following.
valCount(feeds.split(","));
function valCount(t) {
if(t[0].match(/test_user_.*/))
var testUser = t[0].match(/\d+$/);
}
Obviously there is the possibility that sometimes there will only be 1 key in the array and some times 2 or 3, so t[0] won't always be test_user_
I need to somehow pass the array to a function and perform some sort of matching, if array key starts with test_user_ then grab the value and assign it to a define variable.
Thanks guys for all your help!
You can't (reasonably) create variables with dynamic names at runtime. (It is technically possible.)
Instead, you can create object properties:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":"); // Splits the string on the :
obj[parts[0]] = parts[1]; // Creates the property
});
Now, obj["test_user_201508_20150826080829.txt"] has the value "12345".
Live Example:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":");
obj[parts[0]] = parts[1];
});
snippet.log(obj["test_user_201508_20150826080829.txt"]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can do it like this, using the split function:
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
console.log(feed.split(/[:]/));
}
This outputs:
["test_user_201508_20150826080829.txt", "12345"]
["test_user_list20150826", "666"]
["test_list_Summary20150826.txt", "321"]
Use the split method
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
feedMap = {}
for (i = 0; i < feeds.length; i++) {
var temp = feeds[i].split(':');
feedMap[temp[0]] = temp[1];
}
Yields:
{
"test_user_201508_20150826080829.txt":"12345",
"test_user_list20150826":"666",
"test_list_Summary20150826.txt":"321"
}
And can be accessed like:
feedMap["test_user_201508_20150826080829.txt"]
Here is a codepen
it is not very good idea but if you really need to create variables on-the-run here's the code:
for (i = 0; i < feeds.length; i++)
{
var feed = feeds[i];
window[feed.substring(0, feed.indexOf(":"))] = feed.match(/\d+$/);
}
alert(test_user_201508_20150826080829)
Of course you cannot have any variable-name-string containing banned signs (like '.')
Regards,
MichaƂ

Creating Objects inside objects using a Constructor

In the below code I am trying to create an object named "portfolio" inside which
I want to create other objects that contain the properties "stockvalue" and "price"?
var portfolio_create = function(stock,stockvalue,price)
{
for(i in stock)
{
this[stock[i]] = stock[i];
this[stock[i]]["stockvalue"] =stockvalue[i];
this[stock[i]]["price"]=price[i]
}
}
var portfolio = new portfolio_create(["ibm","tcs"],[23,34],[34,45]);
var stock_market = portfolio;
alert(portfolio["ibm"]["stockvalue"]); // undefined
Why does the alert return "undefined" and not 23?
Thnaks in advance.
var portfolio_create = function (stock, stockvalue, price) {
for (var i = 0, len = stock.length; i < len; i++) {
this[stock[i]] = {};
this[stock[i]]["stockvalue"] = stockvalue[i];
this[stock[i]]["price"] = price[i];
}
}
var portfolio = new portfolio_create(["ibm", "tcs"], [23,34], [34,45]);
Don't use for..in for arrays.
this[stock[i]] = stock[i]; replace to this[stock[i]] = {};.
Example
I think there is a little confusion here, between objects and variables.
You can create a real JavaScript class portfolio, which contain a collection of another class stock, which contain 2 variables value and price.
In your portfolio class, you can add a AddStock methode, and a GetStock.
Look at JavaScript Classes, I think you will find your hapiness.
Steeve
And try to use libs like underscore or lodash to get rid of these for loops (each). It is much nicer and more functional.
A little bit shorter:
this[stock[i]] = { stockvalue: stockvalue[i], price: price[i] };

Javascript - use an array for object names then grab properties using a loop

Going crazy trying to do this so I thought I'd get help. I have an array like this:
OBJECTS = ["mainmenu","mainviewer","mainsearch"];
Each of these is an object like this:
mainmenu = {width:250,height:250,backgroundcolor:red};
mainviewer = {width:250,height:250,backgroundcolor:green};
mainsearch = {width:250,height:250,backgroundcolor:blue};
Now the crux of it ... I'm simply trying to get the properties like this:
for (var item in OBJECTS) {
var name = OBJECTS[item];
console.log("the width of "+name+" is "+name.width);
}
The console logs back to me:
the width of mainmenu is undefined
Any help greatly appreciated ...
Your OBJECTS array is an array of strings. It's not an array of objects.
Perhaps you meant it to be this:
var mainmenu = {width:250,height:250,backgroundcolor:"red"};
var mainviewer = {width:250,height:250,backgroundcolor:"green"};
var mainsearch = {width:250,height:250,backgroundcolor:"blue"};
var objects = [mainmenu, mainviewer, mainsearch];
FYI, I also had to put quotes around the color names because symbols like red are not defined.
And, if you want to iterate this with a name, you could do this:
var mainmenu = {name: "mainmenu", width:250,height:250,backgroundcolor:"red"};
var mainviewer = {name:"mainview", width:250,height:250,backgroundcolor:"green"};
var mainsearch = {name: "mainsearch", width:250,height:250,backgroundcolor:"blue"};
var objects = [mainmenu, mainviewer, mainsearch];
objects.forEach(function(item) {
log("the width of "+item.name+" is "+item.width);
});
or, a traditional for loop:
for (var i = 0; i < objects.length; i++) {
var item = objects[i];
console.log("the width of "+item.name+" is "+item.width);
});
Working demo: http://jsfiddle.net/jfriend00/abwgjed2/
Note: it is a bad idea to iterate arrays with the syntax for (item in objects). This iterates all properties of the item object, not just array elements. If there are ES5/ES6 polyfills being used, there may be some extra enumerable properties that will show up in the for (item in objects) iteration. Either use .forEach() or for (var i = 0; i < objects.length; i++).
here is demo
var OBJECTS =
{
mainmenu : {width:250,height:250,backgroundcolor:'red'},
mainviewer : {width:250,height:250,backgroundcolor:'green'},
mainsearch : {width:250,height:250,backgroundcolor:'blue'}
}
for (var item in OBJECTS) {
var name = OBJECTS[item];
console.log("the width of "+item+" is "+name.width);
}

How to get the 'Value' using 'Key' from json in Javascript/Jquery

I have the following Json string. I want to get the 'Value' using 'Key', something like
giving 'BtchGotAdjust' returns 'Batch Got Adjusted';
var jsonstring=
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},]
Wow... Looks kind of tough! Seems like you need to manipulate it a bit. Instead of functions, we can create a new object this way:
var jsonstring =
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},];
var finalJSON = {};
for (var i in jsonstring)
finalJSON[jsonstring[i]["Key"]] = jsonstring[i]["Value"];
You can use it using:
finalJSON["BtchGotAdjust"]; // Batch Got Adjusted
As you have an array in your variable, you have to loop over the array and compare against the Key-Property of each element, something along the lines of this:
for (var i = 0; i < jsonstring.length; i++) {
if (jsonstring[i].Key === 'BtchGotAdjust') {
console.log(jsonstring[i].Value);
}
}
By the way, I think your variable name jsonstring is a little misleading. It does not contain a string. It contains an array. Still, the above code should give you a hint in the right direction.
Personally I would create a map from the array and then it acts like a dictionary giving you instantaneous access. You also only have to iterate through the array once to get all the data you need:
var objectArray = [{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"}]
var map = {}
for (var i=0; i < objectArray.length; i++){
map[objectArray[i].Key] = objectArray[i]
}
console.log(map);
alert(map["BtchGotAdjust"].Value)
alert(map["UnitToUnit"].Value)
See js fiddle here: http://jsfiddle.net/t2vrn1pq/1/

Categories

Resources