Store variable into array javascript - javascript

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;

Related

CasperJS array.push Making Variables Null

I have a custom data type that I am populating, I have verified that data populates correctly but when I try to push it to an array the result is both the array and the custom data type variable are null. Here is an example of what I am doing:
var values = [];
var temp = {};
temp['one'] = rows[i].cells[1].innerText.trim();
temp['two'] = rows[i].cells[2].innerText.trim();
temp['three'] = rows[i].cells[3].innerText.trim();
temp['four'] = rows[i].cells[4].innerText.trim();
values.push(temp);
When I output temp before values.push(temp); all expected values are present. When outputting either values or temp after values.push(temp); both are null.
Very confused, any help is appreciated.
Declare array and object like this..
var values = [];
var temp = {};
Example:
var values = [];
var temp = {};
temp['one'] = 'one';
temp['two'] = 'two';
temp['three'] = 'three';
temp['four'] = 'four';
values.push(temp);
console.log(values);
This was a dumb mistake on my part, nothing to do with the .push but want to answer for anyone else having the problem.
var values = [];
Was declared outside of any function, I thought I could do this and it would be global but that was a newbie mistake.

Concatenate array into string

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)

Use an object-literal as array item

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

Store variable from loop as array to localStorage

What's the way to store result of the for loop as array to localStorage? That is, the result should be: ["./somepage1.html", "./somepage2.html"].
<div class="someclass" href="./somepage1.html">foo</div>
<div class="someclass" href="./somepage2.html">foo</div>
<script>
var foo = document.getElementsByClassName("someclass");
for (var i = 0; i < foo.length; i++)
{
var hrefs = foo[i].getAttribute("href");
console.log(hrefs);
}
</script>
First, create the Array of hrefs.
This uses Array.prototype.map to create a new Array of hrefs from the HTMLCollection of Elements.
var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
return elem.getAttribute("href");
});
Then serialize it using JSON.stringify(), and store it wherever you want in localStorage.
localStorage.foobar = JSON.stringify(arr);
Of course, JSON isn't required to store your data. You can serialize it however you want.
You could have used .join() instead to create a comma-separated string.
var foo = document.getElementsByClassName("someclass");
localStorage.foobar = Array.prototype.map.call(foo, function(elem) {
return elem.getAttribute("href");
}).join(",");
Though this isn't the specific result you described.

Manipulate Json String Jquery

Supposed that I have this JSON STRING that is stored in a vairable:
{"name":"Joene Floresca"},{"name":"Argel "}
How can I make it
["Joene", "Argel"]
You mention you have a string. Use JSON.parse for that. Also, make sure it is an array. Afterwards, you can manually iterate through each object in the array and push the value
var str = '[{"name": "Joene Floresca"},{ "name": "Argel "}]';
var objA = JSON.parse(str);
var values = [];
for (var i = 0; i < objA.length; i++) {
for (var key in objA[i]) {
values.push(objA[i][key]);
}
}
console.log(values);
Assuming your JSON is an array, you can use map:
// Your JSON string variable
var jsonString = '[{"name":"Joene Floresca"},{"name":"Argel "}]';
// Parse the JSON to a JS Object
var jsObject = $.parseJSON(jsonString);
// Use map to iterate the array
var arr = $.map(jsObject, function(element) {
// Return the name element from each object
return element.name;
});
console.log(arr); // Prints ["Joene Floresca", "Argel "]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can iterate over objects inside array and store the names in a second array.
var data = JSON.parse('[{"name":"Joene Floresca"},{"name":"Argel "}]');
var names = [];
data.forEach(function(model) {
names.push(model.name);
});
// names now contains ["Joene Floresca", "Argel"]
alert(names);

Categories

Resources