modify keys of a hash using for loop - javascript

Hey guys I've got 2 dim array and a hash!
Array's second row values and hash keys are set identical!
What I want is to address each hash key using array's row values and change them to array's current column index
Preview example:
{.....,'_11':val, '_12':value, .....}
arr[1][i]='_12'. use this value to address the the unique hash hey and change that key to i. key=i
Is this the right way?
var keyName;
for(var i=0; i<theLength; i++){
keyName = arr[1][i];
hash.keyName=i;
}
10x for your kind help ,BR

Maybe what you want is this:
var keyName;
for(var i=0; i<theLength; i++) {
keyName = arr[1][i];
hash[keyName] = i;
}
Using hash.keyName will always reference a key called keyName, not the key with that variable name.
Since you don't really need the intermediate variable, you can do this:
for(var i=0; i<theLength; i++) {
hash[arr[1][i]] = i;
}

Not sure I follow what you're asking for the rest, but
hash.keyName=i;
should be:
hash[keyName]=i;

Related

Adding objects to Array of objects Javascritp

Probably this is an obvius question, but I'm pretty new on JS.
This is always inserting the same item repeated, it is changing the value of the last item inserted on the array when the object change the value, how can I avoid it and insert all the values that I¡m itereating?
self.user.userSociedadesAreasLink =[];
var userSociedadesAreasLink = {};
for(var i =0 ; i< self.selectedSociedades.length ; i++){
userSociedadesAreasLink.sociedad = self.selectedSociedades[i];
self.user.userSociedadesAreasLink.push(userSociedadesAreasLink);
}
You are using the same object every time to push into the array, only changing the property's value. You have to create a new object everytime to make it as a unique object.
self.user.userSociedadesAreasLink =[];
for(var i =0 ; i< self.selectedSociedades.length ; i++){
var userSociedadesAreasLink = {};
userSociedadesAreasLink.sociedad = self.selectedSociedades[i];
self.user.userSociedadesAreasLink.push(userSociedadesAreasLink);
}
This should solve the issue.
You could just push a new object literal each time. You could also just use a map operation for this.
self.user.userSociedadesAreasLink = self.selectedSociedades.map(s => ({sociedad: s}));

concatenate an increment counter onto the end of an array selector within a json response loop

so I'm looping through a json response and I'm trying to use the counter (var i) to say data.newarray[i].time+i so with each loop the next array is chosen and the time also increases in number. So 1st loop will spit out data.newarray[0].time0 then data.newarray[1].time1 then data.newarray[2].time2 and so on. The bit that is currently failing is my concatenation time+i at the end. How do I format this to work?
var data = JSON.parse(xmlHTTP.responseText);
for(var i=0; i<data.newarray.length; i++)
{
alert(data.newarray[i].time+i);
}
You can access variable property names by using the quoted notation: obj['prop'] instead of obj.prop.
The solution is:
var data = JSON.parse(xmlHTTP.responseText);
for(var i=0; i<data.newarray.length; i++)
{
alert(data.newarray[i]['time'+i]);
}
Try something like this:
for(var i=0; i<data.newarray.length; i++) {
alert(data.newarray[i]['time'+i]);
}

If value is found, take another value from same object

Can anyone tell me if it is possible ?
Basically, I want to search through an array of json objects, and if I find a specific value in one of them, I want to take other values from the same object.
Thanks
var myArrayObject = $.parseJSON(<string>);
for(var i = 0;i <myArrayObject.length; i++){
if (myArrayObject[i] == "<your specified value>") {
// your code here
}
}

won't loop array javascript

Why cant i access my array?
function map(array){
for(i=0; i <=array.length; i++){
var location=array[i].location;
console.log("loc"+location);
var user = array[i].from_user;
console.log("user"+user);
var date = array[i].created_at;
var profile_img = array[i].profile_img;
var text = array[i].text;
var contentString = text;
//geocode(user,date, profile_img, text, contentString,location);
}
}
It gives me undefined for every element.I want to access it and pass the variables to the geocode function.
data structure:
array=[{user: a,user_id: b,date: c,profile_img: d,text: e,contentString: f,url:
g,location:o},{user: a,user_id: b,date: c,profile_img: d,text: e,contentString:
f,url:g,location:o},{user: a,user_id: b,date: c,profile_img: d,text:
e,contentString: f,url: g,location:s}];
dont worry about the values..!
I forgot to mention when i first made the post(question). the location of the array is inserted in the previous function whereas the array didn't include the attribute location from previous functions
When calling the function, use the object literal construct enclosed in an array literal, otherwise all values will be returned as undefined. This is how you should call your function:
map([{ // array literal enclosing an object literal
location : 1,
from_user : 2,
created_at : 3,
profile_img: 4,
text : 5
}]);
Moreover, in your loop, change:
for (i = 0; i <= array.length; i++ ) ...
...to
for (var i = 0; i < array.length; i++) ...
If you have a pre-defined array, name it and pass it to the function like this:
map(arrayObj)
If the array you pass in has a length of 0, the way you're looping it is going to try and access the list element at 0, which is going to be undefined.
However, regardless of the contents of your array, this line will always cause you trouble:
for(i=0; i <=array.length; i++)
When check the length property of your array, it is telling you the number of elements in the array. Since arrays use 0 based indexing, you're going to overrun the bounds of your array with this loop everytime.
var myArray = [1, 2, 3];
myArrary[0]; // This is 1
myArray[2]; // This is 3
Since you are looping between 0 and the length of the array, which happens to be 3, the last element you attempt to access will no exist.
myArray[3]; // Undefined
You need to check i < array.length rather than i <= array.length.
Your code is fine. With the provided input and function you get this:
loco
userundefined
loco
userundefined
locs
userundefined
The reason every user is coming up as undefined is because of:
var user = array[i].from_user;
console.log("user"+user);
The objects you are passing in do not have a from_user property, so naturally it comes up as undefined. Maybe you meant array[i].user_id?
Also, as Aesthete pointed out, you're running outside the bounds of your array because of the way you're checking for length. Do this instead:
for(var i = 0, n = array.length; i < n; i++) {
// your code in here
}
Notice that I preface i with var so it does not become an implicit global. Also, I declare a second variable n so that you only need to access array.length once. This is common practice.
So, putting it all together:
function map(array){
for(var i = 0, n = array.length; i < n; i++){
var location=array[i].location;
console.log("loc"+location);
var user = array[i].user_id;
console.log("user"+user);
var date = array[i].created_at;
var profile_img = array[i].profile_img;
var text = array[i].text;
var contentString = text;
//geocode(user,date, profile_img, text, contentString,location);
}
}
array=[{user: 'a',user_id: 'b',date: 'c',profile_img: 'd',text: 'e',contentString: 'f',url:
'g',location:'o'},{user: 'a',user_id: 'b',date: 'c',profile_img: 'd',text: 'e',contentString:
'f',url:'g',location:'o'},{user: 'a',user_id: 'b',date: 'c',profile_img: 'd',text:
'e',contentString: 'f',url: 'g',location:'s'}];
map(array);
Notice I changed your object properties to strings - this is because you did not give values for these, but you probably don't want to do this. Output is:
loco
userb
loco
userb
locs
userb
All is well. If you are still getting undefined for location then your error must lie with the o property of the objects you're passing in.

Javascript - clearing duplicates from an array object

Hi
I have a javascript array object rapresenting the amount of items sold in a given country, like this:
var data = [{'c1':'USA', 'c2':'Item1', 'c3':100},
{'c1':'Canada', 'c2':'Item1', 'c3':120},
{'c1':'Italy', 'c2':'Item2', 'c3':140},
{'c1':'Italy', 'c2':'Item2', 'c3':110}]
I need to avoid duplicates (as you may see, the last two 'records' have the same Country and the same Item) and sum the amounts; if I was getting data from a database I would use the DISTINCT SUM clause, but what about it in this scenario? Is there any good jquery trick?
You could use an object as a map of distinct values, like this:
var distincts, index, sum, entry, key;
distincts = {};
sum = 0;
for (index = 0; index < data.length; ++index) {
entry = data[index];
key = entry.c1 + "--sep--" + entry.c2;
if (!distincts[key]) {
distincts[key] = true;
sum += entry.c3;
}
}
How that works: JavaScript objects are maps, and since access to properties is an extremely common operation, a decent JavaScript implementation tries to make property access quite fast (by using hashing on property keys, that sort of thing). You can access object properties using a string for their name, by using brackets ([]), so obj.foo and obj["foo"] both refer to the foo property of obj.
And so:
We start with an object with no properties.
As we loop through the array, we create unique key from c1 and c2. It's important that the "--sep--" string be something that cannot appear in c1 or c2. If case isn't significant, you might throw a .toLowerCase in there.
If distincts already has a value for that key, we know we've seen it before and we can ignore it; otherwise, we add a value (true in this case, but it can be just about anything other than false, undefined, 0, or "") as a flag indicating we've seen this unique combination before. And we add c3 to the sum.
But as someone pointed out, your last two entries aren't actually the same; I'm guessing that was just a typo in the question...
jQuery may have an array function for this, but because your two Italy objects are not distinctly unique, your asking for a custom solution. You want to populate a array and check it for duplicates as you go:
var data = [{'c1':'USA', 'c2':'Item1', 'c3':100},
{'c1':'Canada', 'c2':'Item1', 'c3':120},
{'c1':'Italy', 'c2':'Item2', 'c3':140},
{'c1':'Italy', 'c2':'Item1', 'c3':110}]
var newArray = [];
var dupeCheck = {}; // hash map
for(var i=0; i < data.length; i++){
if(!dupeCheck[data[i].c1]){
newArray.push(data[i]);
dupeCheck[data[i].c1] = true;
}
}
test
HTML:
<div id="test"></div>
JS:
var data = [{'c1':'USA', 'c2':'Item1', 'c3':100},
{'c1':'Canada', 'c2':'Item1', 'c3':120},
{'c1':'Italy', 'c2':'Item2', 'c3':140},
{'c1':'Italy', 'c2':'Item1', 'c3':110}];
var
l = data.length, // length
f = "", // find
ix = "", // index
d = []; // delete
for (var i = 0; i < l; i++) {
ix = data[i].c1 + "_" + data[i].c2 + "__";
//var re = new RegExp(ix);
//if (re.test(f))
if (f.indexOf(ix) != -1)
d.push(i);
else
f += ix;
}
for (var i1 = 0; i1 < d.length; i1++){
$("#test").append("<div>for delete: "+d[i1]+"</div>");
}
EDIT
Although chrome works much faster, works only in chrome faster the example with indexOf, then in IE/Opera/Firefox/Safary works faster with an object.
The code created by "# TJ Crowder" is much more efficient.

Categories

Resources