I have an object-literal like this
var data = {name:'racheal', class:'jss2', town:'kaduna'}
I would love this to be in an array like this
[{name:'racheal', class:'jss2', town:'kaduna'}]
You can just create an array with it:
var obj = {name:'racheal', class:'jss2', town:'kaduna'}
var arr = [obj];
Simple use of the push method on an array will achieve this:
var myObj = {name:'racheal', class:'jss2', town:'kaduna'};
var myArray = [];
myArray.push(myObj);
Or, as Tushar says in comments, you can simply initialise a new array with the Object in it:
var myObj = {name:'racheal', class:'jss2', town:'kaduna'};
var myArray = [myObj];
You can read a bit more on Arrays and their various methods and how to use them here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
Related
I have a variable:
var array = [1,2,3]
I want to reverse the array:
array.reverse()
In that example I didn't need to make a temporary variable like this:
var arrayRev = array.reverse()
or like this:
var array = array.reverse()
but some times I need to make a temporary variable with different methods.
in this example I want to join the items in the array:
var array = [1,2,3]
array.join("")
console.log(array)
The result is still [1,2,3] not 123
but if I do this:
var array = [1,2,3]
var arrayJoin = array.join("")
console.log(arrayJoin)
or this:
var array = [1,2,3]
var array = array.join("")
console.log(array)
it works!
why is that so, and how do I know whether to use this:
var array = [1,2,3]
var array = array.join("")
console.log(array)
or this:
var array = [1,2,3]
array.join("")
console.log(array)
thanks!
I have this:
var myarray = [];
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
And I want to get the string:
"first":"$firstelement","second": "$secondelement"
How can I do it?
What you have is invalid (even if it works), arrays don't have named keys, but numeric indexes.
You should be using an object instead, and if you want a string, you can stringify it as JSON
var myobject = {};
myobject["first"] = "$firstelement";
myobject["second"] = "$secondelement";
var str = JSON.stringify(myobject);
console.log(str)
First of all, you'd want to use an object instead of an array:
var myarray = {}; // not []
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
The easiest way, then, to achieve what you want is to use JSON:
var jsonString = JSON.stringify(myarray);
var arrayString = jsonString.slice(1, -1);
JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
var myarray = {};
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
console.log(JSON.stringify(myarray));
Use JSON.strinify()
JSON.stringify(item)
How to store the javascript variable into array?
I have these variable and I wish to store them into array:
var name=document.forms["form"]["name"].value;
var email=document.forms["form"]["email"].value;
var mobile=document.forms["form"]["mobile"].value;
var q1=document.forms["form"]["q1"].value;
var q2=document.forms["form"]["q2"].value;
var q3=document.forms["form"]["q3"].value;
var l1=document.forms["form"]["logo1"].value;
var l2=document.forms["form"]["logo2"].value;
var l3=document.forms["form"]["logo3"].value;
var p1=document.forms["form"]["photo1"].value;
var p2=document.forms["form"]["photo2"].value;
var p3=document.forms["form"]["photo3"].value;
var arr = [];
var name=document.forms["form"]["name"].value;
var email=document.forms["form"]["email"].value;
arr.push(name);
//etc
Using the .push() method
You could also serialize if you are going to post the form.
As simple as
var newArray = [];
newArray[0] = name;
newArray[1] = email;
...
You can try with traditional array:
var myArray = [];
myArray.push(document.forms["form"]["name"].value);
The keys will be numeric (starting from 0).
Or, if you want to preserve string keys, like associative arrays in other languages, you can store your values as an object
var myArray = {};
myArray["name"] = document.forms["form"]["name"].value;
Let's say I have an array named derps and then I make an array inside it:
derps[0]=new Array();
how do I get/set data in the newly created array derps[0]?
Simply do this:
derps[0][0] = 'foo';
derps[0][1] = 'bar';
derps[0].push('foobar');
derps[0] = derps[0].concat([5,6,7]);
// Etc, etc.
console.log(derps[0][1]); // 'bar'
console.log(derps[0][2]); // 'foobar'
console.log(derps[0]); // ["foo", "bar", "foobar", "foobar", 5, 6, 7]
Basically, access derps[0] like you'd access any other array, because it is an array.
I'm not going to list All methods you can use on derps[0] ;-)
Also, instead of:
derps[0] = new Array();
You can use the "array literal" notation:
derps[0] = []; // Empty array, or:
derps[0] = ['foo', 'bar', 'foobar']; // <-- With data.
You can create the array with data already in it:
derps[0] = [1, 2, 3];
You can assign values to the array:
derps[0] = new Array();
derps[0][0] = 1;
derps[0][1] = 2;
derps[0][2] = 3;
You can push values to the array:
derps[0] = new Array();
derps[0].push(1);
derps[0].push(2);
derps[0].push(3);
You can push data into the new array:
derps[0].push("some data");
As an aside: you may also use an array literal to create derps[0]:
derps[0] = [];
Easy:
var derps = [];
derps.push([]);
derps[0].push('foo');
derps[0].push('bar');
If you really wish to instantiate the type of the variable before, you can proceed this way (JSFiddle).
var derps = [];
derps[0] = [];
derps[0][0] = "test";
derps[0][1] = "test2";
document.write(derps[0][1]);
Don't forget to write var if you don't want the variable to be global.
Sorry for my last question being so confusing, I was confused my self, but now I got a proper example:
var obj = {};
obj.entities = [];
obj.entities["player"] = [];
obj.entities["player"]["0"] = [];
obj.entities["player"]["0"]["pos"] = "0,0";
var jsonStr = JSON.stringify(jsonObj);
// {"entities":[]}
console.log(JSON.stringify(obj));
The output of JSON.stringify(obj) is wrong as you can see.
What causes this ?
You're first building an array ([]), then assigning properties to it with non-number keys (player). This is technically possible (as in not causing an error), but it's not what arrays are for.
You should use objects ({}) instead. Also, ["player"] is the same as .player.
var obj = {};
obj.entities = {};
obj.entities.player = []; // array here because you're filling with indices ([0])
obj.entities.player[0] = {}; // object again, because non-indices as keys (`pos`)
obj.entities.player[0].pos = "0,0";
Objects can take any property key. Arrays are a subset of objects, which should only have indices (numbers >= 0) as keys.
Your life would be much easier if you'd define your objects in JSON to begin with:
var obj = {
'entities': [
{'player':{'pos': '0,0'}}
]
};
You're using named array indeces instead of object key/value pairs.
var obj = {};
obj.entities = {};
obj.entities["player"] = {};
obj.entities["player"]["0"] = [];
obj.entities["player"]["pos"] = "0,0";
// {"entities":{"player":{"0":[],"pos":"0,0"}}}
console.log(JSON.stringify(obj));
entities, and entities["player"] and entities["player"]["0"] need to be objects, not arrays.
You're adding properties to these arrays, rather than pushing values onto them. These custom properties are not getting stringified.
The fix is simple:
var obj = {};
obj.entities = {}; // <------------ this is an object now
obj.entities["player"] = {}; // <--------- also an object
obj.entities["player"]["0"] = {}; // <-------- and so on
obj.entities["player"]["0"]["pos"] = "0,0";
I think you have some serious confusions about arrays and objects in javascript. An array ([]) works only with positive integer indexes. In your example you are doing the following:
obj.entities = [];
obj.entities["player"] = [];
You say that obj.entities is an array and then you use player as index. And player is not an integer. So this code makes no sense. On the other hand you could use objects with properties. Those properties can be strings:
obj.entities = {};
obj.entities.player = [];
obj.entities.player[0] = 'foo bar';
You are confusing objects with arrays. The following code will work.
var obj = {};
obj.entities = {};
obj.entities.player = [];
obj.entities.player[0] = {};
obj.entities.player[0].pos = "0,0";
The things you went wrong:
An array can have only integer indexes. So it's incorrect writing a["1"] if you intend to use a as an array.
To be correctly serialized, only an object can have named properties, like object.entities.player or object.entities["player"].