i am looping trough radio buttons to add their values to a javascript object. When i am doing a console.log i am seeing only the last item as an "part of a object" not the whole object.
What am I doing wrong?
var steps = {};
var elements = document.getElementsByTagName("input");
for(var i = 0; i<elements.length; i++) {
if(elements[i].type === "radio")
{
Object.assign(steps, {name: elements[i].value});
}
}
console.log(steps);
You are performing the following in a loop
Object.assign(steps, {name: elements[i].value});
what this basically does is add a key name with value elements[i].value.
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
You need to convert steps to an array and then push all of the keys in it. Alternatively you can change the name key and make it unique although converting it to array would be preferred.
For array you need to do something like this
var steps = [];
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++) {
if (elements[i].type === "radio") {
steps.push({ name: elements[i].value });
}
}
console.log(steps);
Related
I have an situation where I have 3 different arrays with very different amounts of objects in it. I've read many questions and blog posts about this but Im still unsure when to use what.
PS! My biggest problem is that I need to iterate and push (perfect for arrays), also find if exists in array and delete (more suitable for objects). Specific order is not required.
I can't allow having same object in both array1 and array1clicked
because they should perform different actions.
When it's best to use object and when array in my example? What should I replace with object and what should stay as array? Im pretty sure that amounts of objects in it also matters, right?
My current code:
//Objects in arrays are literally custom {objects} with custom prototypes and html
var array1 = [ 20 objects ];
var array1clicked = [];
var array2 = [ 250 objects ];
var array2clicked = [];
var array3 = [ 50 000 objects ];
var array3clicked = [];
//Each object in arrays has event attached
objecthtml.click(function() {
//Add to clicked array
array1clicked.push(thisobject);
//Remove from initial array
var index = array1.indexOf(thisobject);
if (index > -1) {
array1.splice(index, 1);
}
}
//Same with array2 and array3 objects
//Iterations on different conditions
var array1count = array1.length;
var array1clickedcount = array1clicked.length;
//Same with array2 and array3
if(condition1) {
for(a = 0; a < array1count; a++) {
array1[a].div.style.visibility = 'hidden';
}
//Same with array2 and array3 objects
for(a = 0; a < array1clickedcount; a++) {
array1clicked[a].div.style.visibility = 'visible';
}
//Same with array2clicked and array3clicked objects
}
else if(condition2) {
for(a = 0; a < array1count; a++) {
array1[a].div.style.visibility = 'visible';
}
//Same with array2 and array3 objects
for(a = 0; a < array1clickedcount; a++) {
array1clicked[a].div.style.visibility = 'hidden';
}
//Same with array2clicked and array3clicked objects
}
It seems you want a data structure with these operations:
Iteration
Insert
Delete
Search
With arrays, the problem is that searches and deletions (with reindexing) are slow.
With objects, the problem is that the property names can only be strings.
The perfect structure is a set.
var s = new Set();
s.add(123); // insert
s.has(123); // search
s.delete(123); // delete
s.values(); // iterator
In your case, I think you have to use just Array.
In common case, you could use object to keep references and push some values into it, but If you wanna iterate on this, I think you have to use Array.
I have an array of objects
var j = [{"v1":["1","2","3"]}, {"v2":["4","5","6"]}, {"v3":["7","8","9"]}];
I want to check against the object property and perform some sort of logic. I am new to JS so I'm not sure of all the methods I have access to. Basically I want to compare the key value of the object to a string. If the key and the string are the same, then I would remove that object from the array. I'm not sure how to iterate through the object's key in the array.
var str = "v1";
for (var i in j) {
if (i.key == str) { // not sure how to access key value
j.splice(i,1);
}
}
Try this :
var j = [{"v1":["1","2","3"]}, {"v2":["4","5","6"]}, {"v3":["7","8","9"]}];
for (var i = 0; i < j.length; i++)
{
for (var k in j[i]) //do use this if you need to iterate
{
if (k === "mySomething")
{
//...do your stuff
}
}
}
Edit
less verbose :
for (var i = 0; i < j.length; i++)
{
if ("mySomething" in j[i])
{
//...do your stuff
}
}
As we've been discussing in comments, there is seldom a reason to use an array of objects that each only have one property (unless you're using the array to maintain a specific order), so I thought perhaps your problem might be easier if the data was structured like this:
var j = {"v1":["1","2","3"], "v2":["4","5","6"], "v3":["7","8","9"]};
And, you could then iterate it like this:
for (var key in j) {
console.log("j[" + key + "] = ", j[key]);
}
Working demo: http://jsfiddle.net/jfriend00/qdgzso1g/
I have seen many posts about searching nested arrays in javascript but none of them have a way to tell if an item does not exist in the array.
this may sound confusing so here are some examples:
I have 2 arrays oldArray and newArray
structured like this:
array(
[0]=>array([name]:"name"
[location]:"location")
[1]=>array([name]:"name2"
[location]:"location2")
)
both arrays are structured this way.
I need to be able to know which names exist in the old array and not in the new and vice versa.
here is what I have tried:
var name= oldArray[key]['name'];
for (var key in oldArray) {
for(var i= 0, len = newArray.length; i < len; i++){
if(newArray[i]['name'] == name){
//push to array
}
else{
//push to different array
}
}
}
this way I will have an array that contains all names that exist in both arrays and an array that only contains names that exist in the oldArray..
this doesn't seem to work because it is a 1 to 1 comparison. the first array is correct but the array that should only contain the names that exist in the old array is not correct.
Use a boolean to keep track of whether there is a match in the new array. Then after you complete the inner for loop over the newArray, check boolean to see if no matches were found, then push to other array.
var name= oldArray[key]['name'];
for (var key in oldArray)
{
var foundMatch=false
for(var i= 0, len = newArray.length; i < len; i++)
{
if(newArray[i]['name'] == name)
{
//push to array
foundMatch=true;
break;
}
}
if(foundMatch==false)
//push to different array
}
Have you initialized the array for old values?
Are you getting an exception?
Have you debugged it with Chrome?
edit:
I think if you do:
for all old values push if exists and ask again and push, it will keep pushing in an infinite loop.
try to add a break
var name= oldArray[key]['name'];
for (var key in oldArray) {
for(var i= 0, len = newArray.length; i < len; i++){
if(newArray[i]['name'] == name){
//push to array
break;
}
else{
if(i==newArray.length-1)
//push to different array
}
}
}
Consider this Array
var LIST =[];
LIST['C']=[];
LIST['B']=[];
LIST['C']['cc']=[];
LIST['B']['bb']=[];
LIST['C']['cc'].push('cc0');
LIST['C']['cc'].push('cc1');
LIST['C']['cc'].push('cc2');
LIST['B']['bb'].push('bb0');
LIST['B']['bb'].push('bb1');
LIST['B']['bb'].push('bb2');
I can loop through this array like
for(var i in LIST){
console.log(i)//C,B
var level1=LIST[i];
for(var j in level1){
console.log(j)//cc,bb
// etc...
}
}
Fine.. I have few basic questions.
1.How to sort the array in each level?
One level can be sort by .sort(fn) method . How can i pass to inner levels?
2.Why the indexOf method does not works to find the elements in first two levels?
If it's because of the a non string parameter .. how can i search an array items in array if the item is not string?
3.How for(var i in LIST) works ?
I just need a basic understanding of indexing and looping through array ..
Thanks ..
LIST is NOT a three dimensional array in Javascript, it is just an array.
//declare an array which names LIST.
var LIST = [];
//set a property named 'C' of the LIST to be an array.
LIST['C']=[];
//set a property named 'B' of the LIST to be an array.
LIST['B']=[];
//set a property named 'cc' of the 'LIST.C'(which is an array object)
LIST['C']['cc']=[];
//set a property named 'bb' of the 'LIST.B'(which is an array object)
LIST['B']['bb']=[];
The fact is you only need to let the last level to be an array, see my example code below.
function iterateOrderd(obj) {
if (obj instanceof Array) {
obj.sort();
for (var j = 0, l=obj.length; j < l; j++) {
console.log(obj[j]);
}
} else {
var sortable = [];
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
sortable.push(i);
}
}
sortable.sort();
for (var j = 0, l=sortable.length; j < l; j++) {
console.log(sortable[j]);
iterateOrderd(obj[sortable[j]]);
}
}
}
var LIST = {};
LIST['C'] = {};
LIST['B'] = {};
LIST['C']['cc']=[];
LIST['B']['bb']=[];
LIST['C']['cc'].push('cc0');
LIST['C']['cc'].push('cc1');
LIST['C']['cc'].push('cc2');
LIST['B']['bb'].push('bb0');
LIST['B']['bb'].push('bb1');
LIST['B']['bb'].push('bb2');
iterateOrderd(LIST);
You need to know that Array inherits from Object.
In JavaScript, any Object instance is an associative array(!), so acts like an Array in PHP. For example:
var o = {}; // or new Object();
o['foo'] = 'bar';
o[0] = 'baz';
for (i in o) { console.log(i, o[i]); }
Sorting an Object does not make much sense. indexOf would kinda work in theory, but is not implemented.
Arrays are ordered lists. Array instances have push(), length, indexOf(), sort() etc., but those only work for numerical indexes. But again, Array inherits from Object, so any array can also contain non-numerical index entries:
var a = []; // or new Array();
a[0] = 'foo'; // a.length is now 1
a.push('baz'); // a[1] === 'baz'
a.qux = 1; // will not affect a.length
a.sort(); // will not affect a.qux
for (i in a) { console.log(i, a[i]); }
I recommend playing around with arrays and objects, and you'll soon get the point.
What is your sorting criteria ? I mean how will you say array firstArray comes before secondArray?
regarding the for (counter in myArray), counter will take values of an array element in every iteration.
for (counter in [0,1,5]), counter will have values 0, 1 and 5 in the 3 iterations.
In your case, i will have values LIST['B'] and LIST['C'] in the two iterations and j will have values LIST['B']['bb'], LIST['B']['cc'], LIST['C']['bb'] and LIST['C']['cc'].
Both i and j will be arrays.
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.