var stats = JSON.parse(xmlhttp.responseText);
for (index = 0; index <= top; ++index) {
console.log(stats[index]);
}
Return object:
Object {nick: "Okorok", uniq: "STEAM_0:0:XX", teamkill: 4, damage: 619592, deaths: 1727…}
How do I read a property?
If I try "console.log(stats[index]['nick']);", I have an error: "Cannot read property 'nick' of undefined ".
See if stats is an Array of Objects or just a simple Object.
If this is just a simple Object, so you directly use:
console.log(stats['nick']);
or
console.log(stats.nick);
Ok, if it is Object with Objects try this:
for ( key in stats)
{
console.log(stats[key].nick);
}
A sample here: http://jsfiddle.net/2d6bb/3/
I think you have somrthing like an array of objects, like:
stats = [{},{},{},...];
if it is so you can do this:
var stats = JSON.parse(xmlhttp.responseText);
for (var index = 0; index<stats.length;index++){
for (var key in stats[index]) {
console.log(stats[index][key]);
}
}
and if not, it would be an object of objects, like:
stats = { "stat1": {}, "stat2": {}, "stat3": {}, ...];
then you can do this:
var stats = JSON.parse(xmlhttp.responseText);
for (var index in stats){
for (var key in stats[index]) {
console.log(stats[index][key]);
}
}
or it is just simply a single object like:
stats = {}
then you can simply try:
for (var key in stats) {
console.log(stats[key]);
}
so if it is an array-like object you have to different ways, first you can use underscore.js:
stats = _.toArray(stats);
or if you don't want to use the underscore.js the other way is:
var stats2 = []
for (var key in stats) {
stats2.push(key);
}
stats = stats2;
Related
My for loop looks like this,
var myObj = data.response.carTypes;
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
console.log(myObj[key]);
}}
output on console looks like this,
car1
car2
car3
i want to convert this data something like this,
$scope.myArray = [{"cars":car1}, {"cars":car2}, {"cars":car3}]
how can I convert it this way in javascript?
You can use var json = JSON.stringify(jsObject) and var jsObject = JSON.parse("json string")
Just iterate over object and push it into array:
var myObj = data.response.carTypes;
var myArr = [];
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
myArr.push(myObj[key]);
}
}
console.log(myArr);
You can convert the array to JSON using var myJsonArray = JSON.stringify(myArray).
If you're doing this conversion in an older browser, you can use a script.
In order to get your array from the JSON you created, you can use:
var myArray = JSON.parse(myJsonArray)
Also, bear in mind that when you use the same key for several objects in your JSON, the last key with the same name is the one that is going to be used.
Here you have to use javascript object.
say
$scope.myArray = [];
var carlist.cars="";
var carlist={};
carlist is a object which cars is a property
then you can try this way:
var myObj = data.response.carTypes;
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
carlist.cars=myObj[key];
myArray.push(carlist);
console.log(myArray);
}}
You just need to create a new array and push a new object to it in each iteration:
$scope.myArray = [];
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
$scope.myArray.push({cars:myObj[key]});
}
};
Demo:
var myObj = {
a: "Car1",
b: "Car2",
c: "Car3"
};
var carsArray = [];
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
carsArray.push({cars:myObj[key]});
}
};
console.log(carsArray);
I have the following:
var params = {status: [69,71]};
var getTasks = function(params) {
if (params.status.constructor === Array) {
var statuses = params.status;
var newParams = [];
for (var i = 0; i < statuses.length; i++) {
params.status = statuses[i];
newParams.push(params);
}
console.log(newParams);
}
// else {
// ...
// }
};
Calling getTasks(params) logs newParams as:
[ { status: 71 }, { status: 71 } ].
I would expect this to log out
[ { status: 69 }, { status: 71 } ].
What am I missing here?
You're pushing the same Object twice, the most recent change to the Object is visible.
var obj;
for (var i = 0; i < statuses.length; i++) {
// construct obj as desired
obj = {}; // notice this new object is created inside the loop
obj.status = statuses[i];
// push to your array
newParams.push(obj);
}
newParams.push(params); is pushing the object referenced by params to your array. You have an array full of references to the same object, any modifications to that object will be present in each of the array elements, since they are all the same object. Create a new object each time instead of reusing the same one:
for (var i = 0; i < statuses.length; i++) {
newParams.push( { status: statuses[i] } );
}
params is a single object. Inside of your for loop, by doing the following:
for (var i = 0; i < statuses.length; i++) {
params.status = statuses[i];
newParams.push(params);
}
... you are overwriting the status field and pushing the object into the newParams array. However, the object isn't copied - instead, a reference to it is appended to the array. Thus, all elements of newParams are actually the same element.
Essentially, you need to push a clone of the params object into the array in the loop. If you're using jQuery or underscore, an easy way to clone is using the extend() function:
// jQuery
newParams.push(jQuery.extend({}, params));
// or Underscore
newParams.push(_.extend({}, params));
#PaulPro and #PaulS gave correct answers, but there's always an opportunity to learn something new. In this case, I'd recommend to take a look at Array.map which can greatly simplify your code:
function statutify(value) {
return { status: value };
}
var getTasks = function(params) {
if (params.status.constructor === Array) {
var newParams = params.status.map(statutify);
console.log(newParams);
}
// ...
};
Or, it can't hurt to learn something about other libraries like #voithos suggests.
I have an array of objects like this:
var msg = [
{ msg: 'text' },
{ src: 'pic.jpg',id: 21,title: 'ABC' }
];
I'm trying to sanitize the values by iterating manually through the object at the server side, but the module would just return [ '[object Object]', '[object Object]' ] in the console.
socket.on('message', function(msg){
if (io.sockets.adapter.rooms[socket.id][socket.id] == true)
{
var fun = [];
for(var j in msg){
fun[j] = sanitizer.sanitize(msg[j]);
};
console.log(fun);
io.sockets.in(socket.room).emit('message',fun);
}
});
Can anyone show me how to properly sanitize the object?
Something like this should do the trick:
var fun = [];
for(var i = 0; i < msg.length; i++){ // Don't use for...in to iterate over an array.
fun[i] = msg[i]; // Copy the current object.
for(var j in fun[i]){ // Iterate over the properties in this object.
fun[i][j] = sanitizer.sanitize(fun[i][j]); // Sanitize the properties.
};
};
I have an array like this:
var myArray = new Array();
myArray['foo'] = {
Obj: {
key: value
}
};
myArray['bar'] = {
Obj: {
key: value
}
};
When I do console.log(myArray) I just get empty [ ]. And when I try to iterate the array using jQuery's each the function doesn't run.
How can I get the 'foo' and 'bar' parts of the array?
Example code:
console.log(myArray); // [ ]
jQuery.each(myArray, function(key, obj) {
console.log(key); // should be 'foo' following by 'bar'
});
In addition, why does this work:
jQuery.each(myArray[foo], function(obj, values) {
// Why does this work if there are no associative arrays in JS?
});
you can get keys by:
Object.keys(variable name);
it returns array of keys.
You need to define it as an object if you want to access it like that:
var myObj= {};
myObj.foo = ...;
myObj.bar = ...;
Now you can access the properties like myObj["bar"] or myObj.bar
Note:
To loop through all the properties it's wise to add an additional check. This is to prevent you from looping through inherited properties.
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
// Do stuff.
}
}
Array is a collection where each element has an index.
To add element to array you can use push method
myArray.push('someValue');
or set element by index (if length of array < index):
myArray.push('someValue1');
myArray.push('someValue1');
myArray[0] = 'new someValue1';
Note that array is an instance of Object class, so you can add/edit any property of this object:
myArray.foo = '1';
myArray['bar'] = '2';
In this case you will not add new element to array, you defining new properties of object.
And you don't need to create object as Array if you don't wont to use indexes.
To create new object use this code:
var myObj = {};
To get all properties of object see
How to get all properties values of a Javascript Object (without knowing the keys)?
var myArray = {};
myArray['foo'] = { 'key': 'value' }
myArray['bar'] ={ 'key': 'value' }
console.log(myArray)
jQuery.each(myArray['foo'], function(obj, values) {
console.log(obj, values)
});
Demo
With your Array of Objects you could use this function:
var getKeys = function(obj) {
if (!(typeof obj == "object")) return [];
var keys = [];
for (var key in obj) if (obj != null && hasOwnProperty.call(obj, key)) keys.push(key);
return keys;
};
getKeys(myArray) would give you an array of your Keys.
This is basically a cleared up version of underscores _.keys(myArray) function. You should consider using underscore.
// $.each() function can be used to iterate over any collection, whether it is an object or an array.
var myArray = {};
myArray['alfa'] = 0;
myArray['beta'] = 1;
$.each(myArray, function(key, value) {
alert(key);
});
Note: checkout http://api.jquery.com/jQuery.each/ for more information.
I would like to create a structure within javascript. I have a pair of informations, I would like to use, example:
array[1] = new Struct();
array[1].name = "parameter-name";
array[1].value = "parameter-value";
array[2] = new Struct();
array[2].name = "parameter-name2";
array[2].value = "parameter-value2";
This can be on a diffrent page with diffrent values, maybe on element within my array, maybe 2-20..
Later, within my generic javascript, I would like to parse the array and continue with my parameters, example:
for(i=1 to length_of_my_array) {
_tag.array[i].name = array[i].value;
}
How can I realize this with pure javascript? Thanks for any hint!
As long as you don't want any fancy features, it's really easy to create such structures in JavaScript. In fact, the code you posted will almost work, if you replace the new Struct() with this:
array[1] = {};
This creates an empty object, and you can put any properties you want in it, such as name and value.
To create an array, you can do something like this:
var array = []; // empty array
// object literal notation to create your structures
array.push({ name: 'abc', value: 'def' });
array.push({ name: 'ghi', value: 'jkl' });
...
And to iterate over the array:
for (var i = 0; i < array.length; i++) {
// use array[i] here
}
It would be good to find out more regarding the problem you are attempting to resolve.
I don't think there is an object in JavaScript called Struct, unless you define one.
I think what you are looking for is a JavaScript object instead of Struct. There are a number of ways to create a new object, and they can be nested in an array or in other objects.
myArray[0] = new Object();
myArray[0].name = "parameter-name";
myArray[0].value = "parameter-value";
myArray[1] = new Object();
myArray[1].name = "parameter-name2";
myArray[1].value = "parameter-value2";
Notice that I have changed your code in a couple of ways:
1. "array" is named "myArray" to clarify that we are referring to a particular array.
2. The first instance of myArray is 0. Arrays start at 0 in Javascript.
3. Struct is changed to Object.
myarray = [
{
"name":"parameter-name",
"value":"parameter-value"
},
{
"name":"parameter-name2",
"value":"parameter-value2"
}
];
This is an alternative syntax for doing the same thing. It uses "literal notation" to designate an array (the square brackets), and the objects (the curly brackets).
for(var i = 0; i < myArray.length; i++) {
for(key in myArray[i]) {
alert(key + " :: " myArray[i][key]);
}
}
This will loop over the array and alert you for each property of the object.
alert(myArray[0]['value']) //parameter-value
myArray[0]['value'] = "bar";
alert(myArray[0]['value']) //bar
Each property of each object can also be assigned a new value.
You can define arrays and generic objects in pure JavaScript/json:
var array = []; // empty array
array.push({name: 'parameter-name', value: 'parameter-value'});
array.push({name: 'parameter-name2', value: 'parameter-value2'});
console.log(array);
// Output:
// [Object { name="parameter-name", value="parameter-value2"}, Object { name="parameter-name2", value="parameter-value2"}]
You can also define the same array like so:
var array = [
{name: 'parameter-name', value: 'parameter-value'},
{name: 'parameter-name2', value: 'parameter-value2'}
];
As far as looping through the array:
for (var i = 0; i<array.length; i++) {
var elem = array[i];
console.log(elem.name, elem.value);
}
// Outputs:
// parameter-name parameter-value2
// parameter-name2 parameter-value2
I'd store object literals in the array, like so:
var myArray = [];
myArray[0] = {name:"some name", value:"some value"};
myArray[1] = {name:"another name", value:"another value"};
for (i=0; i < myArray.length; i++) {
console.log(myArray[i].name + ' / ' + myArray[i].value);
}
// initialize empty array
var myArray = [];
// fill it with an object - the equivalent of a struct in javascript
myArray.push({
name: 'example-name'
value: 'example-value'
});
// repeat as neccessary
// walking through the array
for (var i = 0; i < myArray.length; i++)
{
// retrieving the record
record = myArray[i];
// and accessing a field
doSomething(record.name);
}
var array = {paramName: 'paramValue', paramName2: 'paramValue2'};
for(i in array) {
_tag.i = array.i;
}
There is no "Struct" in JavaScript only Object
my_array = new Array();
my_array.push({name: 'john', age:31});
my_array.push({name: 'da_didi', age:120});
for (i=0; i<my_array.length; i++)
{
alert(my_array[i].name);
}
How about
function Struct(name, value) {
this.name = name;
this.value = value;
}
arr[0] = new Struct("name1", "value1");
Javascript objects are loose objects: properties can be added and removed dynamically. So making a new Struct(), as you suggest, does -not- guarantee that the returned object will always have the properties you expect it to have. You have to check the availability of properties at the point of usage (duck typing):
var i, element;
for (i = 0; i < array.length; i++) {
element = array[i];
if (Object.hasOwnProperty.call(element, "name")
&& Object.hasOwnProperty.call(element, "value")) {
_tag[element.name] = element.value;
}
}
(Also, I'm just guessing that _tag is an object itself, but that wasn't clear from your example.)
You could probably use a more succinct syntax, but that depends heavily on the values of the properties. For example, you -might- be able to use something like this:
var i, element;
for (i = 0; i < array.length; i++) {
element = array[i];
if (element.name && element.value) {
_tag[element.name] = element.value;
}
}
But you need to realize that the above condition will be false not only if one or both of the properties (name and value) are undefined but also if the value of either or both refers to the empty string, null, 0, NaN, or false.