List array values - javascript

I have an array like this
var cons=Array();
cons[random_text]=random_number;
cons[random_text]=random_number;
...
I want to list all values in cons variable.How can I do this in one loop ?

There are no associative arrays in javascript, the index can be only numbers.
What you're creating is an object with key/value pairs, unless random_text for some reason actually is an integer, which would seem strange.
var cons = {}; // object, not array
cons[random_text] = random_number;
cons[random_text] = random_number;
// iterate
for (var key in cons) {
var value = cons[key];
console.log(key + ' : ' + value);
}
to get an array of the keys in modern browsers, there's also
var key_arr = Object.keys(cons);

Related

$.each() over Key value pair array

I've created my array as following:
var test = [];
test['pizza'] = 4;
test['pudding'] = 6;
I'm used to use $.each to loop over my array and print out the values and indexes. I'm doing this as following:
$.each(test, function (index, value){
console.log(value);
});
Yet somehow it does only print [].
How would one loop through an array as mine to print out the values 4 and 6?
each will only iterate over iterable properties of the array, pizza and pudding are not iterable properties.
As you require the key-value pair, declare the variable as object.
var test = {};
test['pizza'] = 4;
test['pudding'] = 6;
You don't need jQuery to iterate through a Javascript array, just use for.
var test = [];
test['pizza'] = 4;
test['pudding'] = 6;
for (var k in test) {
if (test.hasOwnProperty(k)) {
console.log('Key: ' + k + ' Value: ' + test[k]);
}
}
// Key: pizza Value: 4
// Key: pudding Value: 6
You don't need to declare test as an object for this (suggested in other answers), array is fine.
By using for you are improving performance of your application. See here.
In both Firefox and Chrome, the for loop is well over 100x faster than
the others.
you might want to choose what happens to serve your needs. I guess you were trying to get a array of objects which will look something like [{},{},{},{}]
Here test is an object(Associative array), not an array so you need to declare it as javascript object
var test = {};
test['pizza'] = 4;
test['pudding'] = 6;
$.each(test, function (index, value){
console.log(value);
});

can i have two objects with the same property names? [duplicate]

This question already has an answer here:
Javascript object when setting property all properties with same name are set
(1 answer)
Closed 1 year ago.
whenever i try to change the first object in the array's y, all the other objects y properties in my array also change, is there any way to prevent this, or a way to add multiple objects to an array that share the same properties ?
i have been trying everything to fix this(i was creating a game that uses a similar array for bullets firing and whenever i changed the y property of the first item in my array all the other y properties in the array changed with it) and i thought that this might be the problem ?
var obj = {x:30,y:20};
var arr = [];
for(var i = 0;i<3;i++) {
arr.push(obj);
}
arr[0].y = 40;
document.write(arr[0].y + " " + arr[1].y);
You can fix this by defining an object inside of .push().
This creates a new object for each element of the array, instead of the array containing multiple references to the same object.
var arr = [];
for(var i = 0;i<3;i++) {
arr.push({x:30, y:20});
}
arr[0].y = 40;
document.write(arr[0].y + " " + arr[1].y);
In JavaScript, objects are stored in memory as pointers to the values inside the object. This is different to how primitive data types (int, char, etc.)
A good way to show this is to try printing out the object, vs printing out an int:
HTML:
<div id="anelementhere"></div>
<div id="anotherelementhere"></div>
JS:
var x = 5;
var obj = {x:30,y:20};
document.getElementById("anelementhere").innerHTML = x;
document.getElementById("anotherelementhere").innerHTML = obj;
JSFiddle: https://jsfiddle.net/d3ohpqqp/
You should be able to see something akin to:
5
[object Object]
Now, knowing this, what's stored in the array is NOT {{x:30, y:20}, {x:30, y:20}, {x:30, y:20}}, but {[object Object], [object Object], [object Object]}, which all point to ONE {x:30, y:20}
This is what makes all the y properties change after changing one. Now a simple solution, as #IrkenVader has shown is where you initialize the object when you put it into the array.
However, if for some reason you still want the original object outside of the array, this is another solution:
var obj = {x:30,y:20};
var arr = [];
for(var i = 0;i<3;i++) {
arr.push({x:obj.x, y:obj.y});
}
arr[0].y = 40;
document.write(arr[0].y + " " + arr[1].y);
JSFiddle: https://jsfiddle.net/9gzyr38x/
you are making a single obj and passing a reference to the same object, 4 times in your array
instead you could try creating new objects in each iteration:
var arr = [];
for(var i = 0;i<3;i++) {
arr.push({x:30,y:20});
}
arr[0].y = 40;
document.write(arr[0].y + " " + arr[1].y);
You could also look up the various ways to "clone" an object. angular, jquery and underscore all provide methods to do so, or you can check out How to clone js object?
As well as the answer #IrkenInvader gave, you can also use jQuery to very easily perform a deep-copy of an object:
var obj = {x: 30, y: 20};
var arr = [];
for(var i = 0; i < 3; i++) {
arr.push(jQuery.extend(true, {}, obj));
}
arr[0].y = 40;
document.write(arr[0].y + " " + arr[1].y);

javascript object, concatenate duplicate keys while keeping multiple values

I have javascript objects that follow this pattern. Keys are to the left of the = sign, values to the right. The keys that are duplicates need to be concatenated to one key while keeping all the values.
var arrUnique = ['arTitle=randomword','arTitle=random','beTitle=rand1','bnTitle=whatever','caTitle=mango','caTitle=mangoes']
Becomes this string:
arTitle = ['randomword','random' ], beTitle = ['rand1'], bnTitle = ['whatever'], caTitle = ['mango','mangoes']
Here is where I am at so far. Create an object with all the keys using regex. Then create a regex construction which loops through each object in keys and pushes to x only when it matches more then 1.
var keys = (/\w{2}Title=/gi);
var x = [];
for (i = 0; i < arrUniqueCount; i++){
var regexp = new RegExp(keys[i], "gi");
var str2 = arrUniqueString.match(regexp).length;
if (str2 > 1){
x.push(regexp[i])}
}
alert("repeats: " + x);
Next I was thinking of using regex to replace and match etc to finally get my outcome. I am finding this stage difficult. Would anybody mind sharing a better way?
I would go the route of just sliptting at the '=' sign then adding them to an object based on the key at index position 0 of that split.
var arrUnique = ['arTitle=randomword', 'arTitle=random', 'beTitle=rand1', 'bnTitle=whatever', 'caTitle=mango', 'caTitle=mangoes'];
//object to collect the final result in
var result = {};
//go through each item and split on the equal
//this will create an array or arrays that contain your key/value
arrUnique.map(function(x) {
return x.split("=");
}).forEach(function(item) {
//if the key doesn;t yet exist in the object declare it as an empty array
if (!result[item[0]]) {
result[item[0]] = [];
}
//push the value onto this key
result[item[0]].push(item[1]);
});
console.log(result);

for in loop behaving strangely in javascript

var friends=['2','3'];
console.log(friends);
var rooms=[];
for(var friend in friends){
var room = 'userid'+friend+'friends';
console.log(room);
rooms.push(room);
}
console.log(rooms);
this outputs
[ '2', '3' ]
userid0friends
userid1friends
[ 'userid0friends', 'userid1friends' ]
3 is neglected entirely, and it behaves even more strangely on my node.js server
friend here is the index of your array, not the value at the index
var room = 'userid'+friends[friend]+'friends';
Plus when looping through an array I don't recommend to use for..in loops, you can use Array.prototype.map or plain for loop with the length of your array
Array map example:
var friends=['2','3'];
console.log(friends);
var rooms= friends.map(function (friend, index) {
return 'userid' + friend + 'friends';
});
console.log(rooms);
Plain for loop:
var friends=['2','3'];
console.log(friends);
var rooms=[];
for (var i = 0, l = friends.length; i < l; ++i) {
var room = 'userid' + friends[i] + 'friends';
console.log(room);
rooms.push(room);
}
console.log(rooms);
The for in structure is used to loop the object, for key in object, key is the property name of the object, when used for an array, key will be the array index.
You could use .map to get your result:
var friends=['2','3'];
var rooms = friends.map(function(e) {
return 'userid'+e+'friends';
});
A for in loop is used to enumerate objects. You are trying to iterate over an array. A better technique for iterating would be a regular for loop or the Array.forEach() method.
In a for in loop, the variable contains the key, not the value. To get the value, use the key:
for(var i in friends){
var friend = friends[i];
...
}
But, again, this enumerates an object, including any properties besides the array elements. This means that if any code adds a method to Array.prototype, that method will also be enumerated. Using .forEach() is better:
friends.forEach(function (friend, i) {
...
});
Better yet, since you are trying to create a new Array based on the contents of another, use Array.map(). That is exactly what it's for.
var rooms = friends.map(function (friend, i) {
return 'userid'+friend+'friends';
});

Stringify an JS Object in Asc order

I have an js object like
{
a: 1,
b: 2,
c: 3
}
I wanted to stringify the above object using JSON.stringify with the same order. That means, the stringify should return me the strings as below,
"{"a":"1", "b":"2", "c":"3"}"
But it is returning me like the below one if my js object has too many properties say more than 500,
"{"b":"2", "a":"1", "c":"3"}"
Is there any option to get my js object's json string as in sorted in asc.
If the order is important for you, don't use JSON.stringify because the order is not safe using it, you can create your JSON stringify using javascript, to deal with string values we have 2 different ways, first to do it using regexp an replace invalid characters or using JSON.stringify for our values, for instance if we have a string like 'abc\d"efg', we can simply get the proper result JSON.stringify('abc\d"efg'), because the whole idea of this function is to stringify in a right order:
function sort_stringify(obj){
var sortedKeys = Object.keys(obj).sort();
var arr = [];
for(var i=0;i<sortedKeys.length;i++){
var key = sortedKeys[i];
var value = obj[key];
key = JSON.stringify(key);
value = JSON.stringify(value);
arr.push(key + ':' + value);
}
return "{" + arr.join(",\n\r") + "}";
}
var jsonString = sort_stringify(yourObj);
If we wanted to do this not using JSON.stringify to parse the keys and values, the solution would be like:
function sort_stringify(obj){
var sortedKeys = Object.keys(obj).sort();
var arr = [];
for(var i=0;i<sortedKeys.length;i++){
var key = sortedKeys[i];
var value = obj[key];
key = key.replace(/"/g, '\\"');
if(typeof value != "object")
value = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
arr.push('"' + key + '":"' + value + '"');
}
return "{" + arr.join(",\n\r") + "}";
}
The JavaScript objects are unordered by definition (you may refer to ECMAScript Language Specification under section 8.6, click here for details ).
The language specification doesn't even guarantee that, if you iterate over the properties of an object twice in succession, they'll come out in the same order the second time.
If you still required sorting, convert the object into Array apply any sorting algorithm on it and then do JSON.stringify() on sorted array.
Lets have an example below as:
var data = {
one: {
rank: 5
},
two: {
rank: 2
},
three: {
rank: 8
}
};
var arr = [];
Push into array and apply sort on it as :
var mappedHash = Object.keys( data ).sort(function( a, b ) {
return data[ a ].rank - data[ b ].rank;
}).map(function( sortedKey ) {
return data[ sortedKey ];
});
And then apply JSON.stringy :
var expectedJSON = JSON.stringify(mappedHash);
The output will be:
"[{"rank":2},{"rank":5},{"rank":8}]"

Categories