when i type the following code statement i get the image attached.Now i want to access the property "label" that is inside each of these objects. how can i go through each of these objects and get their "label" properties?
item.getModel().oData;
i have tried the following code but it failed to work:
var labelText = item.getModel().oData;
labelText.forEach(function(entry) {
var c = entry.StreetName;
});
An example of one of the items:
Because it's an Object and not an Array, you should use Object.keys or some other method to access each property of the object instead. For example:
var labelText = item.getModel().oData;
var keys = Object.keys(labelText);
for (var i = 0; i < keys.length; i++) {
var c = labelText[keys[i]].StreetName;
}
A succinct way of iterating properties of an object, usisng forEach and the keys method of Object
var labelText = item.getModel().oData;
Object.keys(labelText).forEach(function(entryName) {
var c = labelText[entryName].StreetName;
});
var labelText = item.getModel().oData;
$(labelText).each(function(index,entry) {
var c = entry.StreetName;
});
Related
I mostly develop in Java, but I presently need to do some work using JavaScript.
I have data that I need to group by two dimensions: first by gender, and then by language. The object to be grouped comes like so:
var items =[ {
"language":"english",
"gender":"male",
...//twelve other fields
},
...
]
This is what I've tried:
var myMap = {};
for(var i=0; i<items.length;i++){
var item = items[i];
var _gender = item["gender"];
var _lang = item["language"];
myMap[_gender][_lang].push[item];
}
I assumed the above would work, but it’s not working. It keeps returning this error:
Uncaught TypeError: Cannot read property 'undefined' of undefined
Note: In Java, I would be creating a map of arrays.
One problem:
When you call myMap[_gender][_lang].push[item];, what you are actually doing is adding a key to the Object myMap, with the current value of _gender, and turning it into an Object, which you then create a new key for, set to the value of _lang. In addition, .push() is a function used with arrays, to add a new item onto the end of the array. If you want to add a new key and value to an Object, all you have to do is just call that key and assign it a value. Here's an example.
var obj = {
ex1 : 'example 1',
ex2 : 'example 2'
};
console.log(obj);
obj.ex3 = 'example 3';
console.log(obj);
//The code below will simply log 'undefined' in most consoles(it doesn't happen to do so in this snippet).
console.log(obj.ex4);
Here's my suggestion(assuming I correctly understand what you're trying to do):
var items = [{
"language":"english",
"gender":"male",
},
//...more below
];
myMap = [];
for(var i = 0; i < items.length; i++){
myArray = [];
var item = items[i];
var _gender = item["gender"];
var _lang = item["language"];
myArray.push(_gender);
myArray.push(_lang);
myMap.push(myArray);
}
You are doing totally wrong. First of all myMap is object not an array so you can not use myMap.push().
You can achieve like this.
var items = {
"language":"english",
"gender":"male"
}
var myMap = {};
for(var key in items){
var myArray = [];
var _gender = items["gender"];
var _lang = items["language"];
myArray.push(_gender);
myArray.push(_lang);
myMap.item = myArray;
console.log(myMap);
}
for add 2-d array read this. 2-D Array in javascript
I have a job to refractor strings to start using json so they can just pass json objects. So I have made array of names and then I'm trying to go through and make key and values but I'm getting an error in the console that it cant find x of no value. Can someone point me in the right direction?
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification', 'WorkQueue', 'TicketState',................ to long to post];
$().each(newName, function (key, value) {
key = newName[this];
value = newValues[this] = $('#' + key).val();
newArray = [key][value];
newArray = JSON.stringify(newArray);
alert(newArray);
$('.results').html(origArray[TicketNumber]);
});
I'm assuming you have "newValues" and "origArray" defined elsewhere?
In any case you'll need to at least adjust the following:
"$().each" should be $.each
"newArray" should be defined outside and you should use newArray[key] = value
you don't have a variable "TicketNumber" defined and so you should wrap "TicketNumber" in quotes
this is a reserved word so you shouldn't use it in "newName[this]" or "newValues[this]"
I suggest using a for loop instead of $.each() based on what you're trying to do inside.
https://msdn.microsoft.com/en-us/library/bb299886.aspx
var origArray = [];
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification'
];
for (var i = 0; i < newName.length - 1; i++) {
var object = {};
object[newName[i]] = newName[i];
object = JSON.stringify(object);
origArray.push(object);
}
It seems complicated for me.
First, I have this list:
liste_path_categories.push(
{ index: null
, letter: "letter1"
, type: key
, picture_url: "url1"
, id_categ: null
, response: "Answer here"
});
What I want is to extract from this big list an object in this form:
data["String1"]["String2"]= String3
With :
String1=list_path_categories[i].letter
String2=list_path_categories[i].id_categ
String3=list_path_categories[i].response
example:
data['A']['12'] : "A_answer"
To declare the data i make this:
var data = new Object(new Object);
How I can set all the values in data?
You can use the Array.forEach method to iterate through liste_path_categories and construct your data object.
Example:
var liste_path_categories = [];
var data = {};
liste_path_categories.push(...);
...
liste_path_categories.push(...);
liste_path_categories.forEach(function(element) {
data[element.letter] = {};
data[element.letter][element.id_categ] = element.response;
});
jsFiddle example : http://jsfiddle.net/3ZvNf/
Your question is pretty vague but do you mean something like this?
Setting a dynamic property in an object wich belongs to another object?
data['A']['12'].answer = "A_answer"
Instead of using strings, you have to use the variables in your property access:
var data = {};
if (!data[String1]) {
data[String1] = {}; // make sure that data[String1] exists and is an object
}
data[String1][String2] = String3;
If you want to do this for elements in the array, you have to iterate over the array.
P.S.: I recommend to use more expressive variable names than StringX.
first create the constructor (in OOP terminology):
var ctor_object = function(letter,id_categ,response)
{
this.letter = letter;
this.id_cated = id_categ;
this.response = response;
}
(in genereal you should omit the ctor_ syntax and name it directly after the name of the class of your object)
then use your constructor upon your list of categories:
var length = liste_path_categories.length,
element = null;
for (var i = 0; i < length; i++)
{
element = liste_path_categories[i];
my_obj = new ctor_object(element.letter,element.id_categ,element.reponse)
// Do something with my_obj
}
I'm running this code.
var output = {"records": []};
for(i = 0; i < data.length; i++)
output.records[i] = { propertyName : data[i][propertyName] }
I expected the output to be on the following form.
{ "cat" : "mjau" }
{ "dog" : "woff" }
Instead, I get to my surprise this.
{ "propertyName" : "mjau" }
{ "propertyName" : "woff" }
How can I get variable propertyName?
I'm trying to create a parser that will create a number of records that are all cat but, when called from an other place, the records should have dog property instead. I wish to avoid creating two different code pieces for that.
I've found this question, which I suspect contains the answer to my issue. However, due to ignorance, I don't get it.
Keys in object literals won't be evaluated in JavaScript. So, you need to create an empty object ({}) and then assign the key dynamically:
output.records[i] = {};
output.records[i][propertyName] = data[i][propertyName]
var a = {b:'c'}
is just like
var a = {};
a['b'] = 'c';
What you want is
a[b] = c
that is
output.records[i] = {};
output.records[i][propertyName] = data[i][propertyName];
You have in this MDN document : Working with objects.
In { propertyName : data[i][propertyName] } the property name part should be constant string. It you pass a variable it wont fetch its value.
What you have to do is
for(i = 0; i < data.length; i++){
var a = {};
a[propertyName] = data[i][propertyName];
output.records.push(a);
}
You can try this:
'"' + propertyName + '"' : ...
is there a way to find the number of children in a javascript object other than running a loop and using a counter? I can leverage jquery if it will help. I am doing this:
var childScenesObj = [];
var childScenesLen = scenes[sceneID].length; //need to find number of children of scenes[sceneID]. This obviously does not work, as it an object, not an array.
for (childIndex in scenes[sceneID].children) {
childSceneObj = new Object();
childSceneID = scenes[sceneID].children[childIndex];
childSceneNode = scenes[childSceneID];
childSceneObj.name = childSceneNode.name;
childSceneObj.id = childSceneID;
childScenesObj .push(childSceneObj);
}
The following works in ECMAScript5 (Javascript 1.85)
var x = {"1":1, "A":2};
Object.keys(x).length; //outputs 2
If that object is actually an Array, .length will always get you the number of indexes. If you're referring to an object and you want to get the number of attributes/keys in the object, there's no way I know to that other than a counter:
var myArr = [];
alert(myArr.length);// 0
myArr.push('hi');
alert(myArr.length);// 1
var myObj = {};
myObj["color1"] = "red";
myObj["color2"] = "blue";
// only way I know of to get "myObj.length"
var myObjLen = 0;
for(var key in myObj)
myObjLen++;