We have an empty object:
var obj = {};
I would like to make a for loop which with each iteration adds a new obj = {value: i, next: i+1}
Simply use an array of objects and for every iteration push this values on it:
var obj=[];
for(var i=1;i<10;i++){
obj.push({value: i, next: i+1});
}
This is a DEMO Fiddle.
For each iteration give the obj.value and the obj.next, take a look at JavaScript Object Properties for futher information.
Not that sure what you mean but what about this
var obj = [];
function Obj(i){
this.value = i;
this.next = i+1;
}
for (var i= 0;i<10;i++){
obj.push(new Obj(i));
}
Instead of an object of objects an array of them
Related
I read an article named Optimization killers, and in 5.2.3. The object contains enumerable array indices, It says :
Workaround: Always use Object.keys and iterate over the array with for loop. If you truly need all properties from entire prototype chain, make an isolated helper function:
function inheritedKeys(obj) {
var ret = [];
for(var key in obj) {
ret.push(key);
}
return ret;
}
I don't understand what it means.
In the above code, there is still a for...in, so function inheritedKeys can't be optimized, how can it be an isolated helper function?
That's just an example on how to get keys from an object doing it with the for in loop.
He actually tells you that in order to make it faster you should use Object.keys when you want to get keys of an object.
Here's the test performance.
http://jsperf.com/forintest
So DON'T use this to retrieve object keys
function inheritedKeys(obj) {
var ret = [];
for(var key in obj) {
ret.push(key);
}
return ret;
}
var myobject= {"1":"a","2":"b"};
var calculation = inheritedKeys(myobject);
Use this instead it's more clean simple to read and faster
var myobject= {"1":"a","2":"b"};
var calculation = Object.keys(myobject);
Here's a test comparing for in using with array and a normal for loop.
http://jsperf.com/forinarray
You can see that the for loop is way faster.
DON'T use this
function iteratesOverArray() {
var arr = [1, 2, 3];
var newArr = [];
for (var index in arr) {
newArr.push(index);
}
return newArr;
}
var arr = iteratesOverArray();
Use this instead
function iteratesOverArray() {
var arr = [1, 2, 3];
var newArr = [];
for (var i=0,l=arr.length-1;i<=l;i++) {
newArr.push(i);
}
return newArr;
}
var arr = iteratesOverArray();
I have been working with JavaScript for quite a time, but have never encountered this issue:
var objArr = [];
var obj = {
id:null,
name:''
}
//Type 1: Why This do not work
//create an array of 5 object
for(var i=0; i<3; i++){
obj.id = i;
console.log(obj);
objArr.push(obj); //What is wrong here
}
console.log(JSON.stringify(objArr)); // Have 5 objects in the array, But if you see this object is display the last object
//output : [{"id":2,"name":""},{"id":2,"name":""},{"id":2,"name":""}]
//Type 2: Why This Works and why the above object works
var objArr=[];
//create an array of 5 object
for(var i=0; i<3; i++){
console.log(obj);
objArr.push({"id":i, "name":''});
}
console.log(JSON.stringify(objArr));
//output : [{"id":0,"name":""},{"id":1,"name":""},{"id":2,"name":""}]
Maybe I have miss understood the objects here. can you please tell me why is this behavior.
I have a jsfiddle.net Fiddle
In the first example, you have one (only one) object, obj. You are creating an array of 3 (not 5) objects, but each position in your array refers to the same object.
When you set obj.id, you are changing it for the one and only object, which is referenced at each position in the array.
In the second example, you are creating a new object each time:
{"id": i, "name":''} // this creates a new object
So it works.
Try to use something like this:
var objArr=[];
for(var i=0; i<3; i++){
var obj = {};
obj['id'] = i;
obj['name'] = null;
console.log(obj);
objArr.push(obj);
}
console.log(JSON.stringify(objArr));
You just need to create a new obj inside the first for loop. You're just editing the current obj defined outside the for loop. So each loops sets the id of the one obj to it's i value, then you're inserting a copy of that into the array, so on the next loop, each reference to the original object is changed.
Inside the for loop, I just added 'var' so obj is a new one, not the same one that is in the parent scope:
var obj.id = i;
But you may want to reformat it a bit better than that.
I have a class like below;
function Request()
{
this.CompanyId;
this.Password;
this.SessionId;
this.UserId;
this.UserName;
}
I create an object and want to get byte array of object;
var request = new Request();
request.UserName = GlobalProcess.SessionInfo.Server.UserName;
request.Password = GlobalProcess.SessionInfo.Server.Password;
request.CompanyId = GlobalProcess.SessionInfo.SelectedDatabase.CompanyId.toString();
request.UserId = GlobalProcess.SessionInfo.UserId.toString();
request.SessionId = GlobalProcess.SessionInfo.SessionId.toString();
var requestbinary = GetByte(request);
console.log(requestbinary);
My GetByte function is;
function GetByteArrayFromStringArray(parameter)
{
var mainbytesArray = [];
for (var i = 0; i < parameter.length; i++)
mainbytesArray.push(parameter.charCodeAt(i));
return mainbytesArray;
}
In console, I get empty array. What am I doing wrong?
Try this
function GetByteArrayFromStringArray(parameter) {
for (var key in parameter) { // loop through properties
var mainbytesArray = [];
for (var i = 0; i < parameter[key].length; i++)
mainbytesArray.push(parameter[key].charCodeAt(i));
}
return mainbytesArray;
}
It loops through the properties and gets you the array of theese
You're passing an object to a function that expects a string (I think). Your object has no "length" property, so the loop does nothing at all.
You could have the function iterate through the object's properties, I suppose, and accumulate an array from the values of each one. That would not be terribly useful, I don't think, as in JavaScript you're not guaranteed that you'll iterate through an object's properties in any particular order.
If I create a JavaScript object like:
var lst = [];
var row = [];
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
And then convert it to a string:
JSON.stringify(lst);
The result is an object containing an empty object:
[[]]
I would expect it to serialize like:
[[Col1 : 'val1', Col2: 'val2']]
Why do the inner objects properties not serialize?
Code snippet at JSFiddle.
Because row is an array, not an object. Change it to:
var row = {};
This creates an object literal. Your code will then result in an array of objects (containing a single object):
[{"Col1":"val1","Col2":"val2"}]
Update
To see what really happens, you can look at json2.js on GitHub. This is a (heavily reduced) snippet from the str function (called by JSON.stringify):
if (Object.prototype.toString.apply(value) === '[object Array]') {
//...
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
//...
}
//...
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
//...
}
//...
}
//...
Notice that arrays are iterated over with a normal for loop, which only enumerates the array elements. Objects are iterated with a for...in loop, with a hasOwnProperty test to make sure the proeprty actually belongs to this object.
You use your inner array like an object, so make it an object instead of an array.
var lst = [];
var row = {};
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
or use it as an array
var lst = [];
var row = {};
row.push( 'val1' );
row.push( 'val2' );
lst.push(row);
You want row to be a dictionary, not a vector. Define it like this:
var row = {};
Since an array is a datatype in JSON, actual instances of Array are stringified differently than other object types.
If a JavaScript Array instance got stringified with its non-numeric keys intact, it couldn't be represented by the [ ... ] JSON array syntax.
For instance, [ "Col1": "val1"] would be invalid, because JSON arrays can't have explicit keys.
{"Col1": "val1"} would be valid - but it's not an array.
And you certainly can't mix'n'match and get { "Col1": "val1", 1, 2, 3 ] or something.
By the way, this works fine:
var lst = [];
var row = {};
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
alert(JSON.stringify(lst));
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.