how do i get values from multidimensionnal table in javascript? - javascript

i have an array of urls. I insert into it values like this :
var replacementArray=[];
function insert(arr,url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
This is an example of one such URL array:
replacementArray:{
[url:"tuto.com", shorturl:"xfm1")],
[url:"youtube.com", shorturl:"xfm2")],
[url:"google.com",shorturl:"xfm3"]}
I have to compare the shorturl of this array with a string. If the strings match then i retrieve the url. Here is my first attempt at doing this :
var chaine="xfm1";//this is an example
for(var j=0;j<replacementArray.length;j++)
if (replacementArray[j][shorturl]==chaine){
var url= replacementArray[url];
}
This seems to not be working. Why is that?

Associative arrays with arbitrary keys don't exist in javascript
You can have data that works as an associative array, but then you need to use an object to store the keys.
The example data you provided is not valid JS. It is an object of arrays instead of being an array of objects. For your function to work as expected, the data
needs to be in the following format:
[
{
url: 'tuto.com',
shorturl: 'xfm1'
},
{
url: 'youtube.com',
shorturl: 'xfm2'
},
// etc...
]
The [] is for creating an array, which will have numeric indexes only.
The {} creates objects that can store key-value pairs like an associative array in other languages.
So in your function you can loop through the array indexes by incrementing i and access the values associated with your keys using replacementArray[i].shorturl or replacementArray[i]['shorturl'] (notice the string) - the way you do it is up to your preference, they both work the same.
Hope this helps!

var arr=[];
function insert(arr,url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
insert(arr,"google.com", "xfm.io1");
insert(arr,"gogle.com", "xfm.io2");
insert(arr,"gole.com", "xfm.io3");
function getUrl(yourVariable){ //chaine
for(var j=0;j<arr.length;j++)
if (arr[j].shorturl == chaine){
return arr[j].url;
}
return null;//not found yourVariable
}
var chaine= "xfm.io1"; //your Short URL
console.log(getUrl(chaine)); //testing the function
First of all you given: (which is not an acceptable data structure)
replacementArray:{
[url:"tuto.com", shorturl:"xfm1")],
[url:"youtube.com", shorturl:"xfm2")],
[url:"google.com",shorturl:"xfm3"]}
which must be like this: (array of objects)
replacementArray:[
{url:"tuto.com", shorturl:"xfm1"},
{url:"youtube.com", shorturl:"xfm2"},
{url:"google.com",shorturl:"xfm3"}]
Then to get shortUrl code will be like
function getUrl(yourVariable){ //chaine
for(var j=0;j<replacementArray.length;j++)
if (replacementArray[j].shorturl == chaine){
return replacementArray[j].url;
}
return null;//not found yourVariable
}

Read over these corrections/suggestions:
As others have mentioned, you should create an array of objects, instead of an object with arrays
Reference the property 'shorturl' either using array syntax (i.e. replacementArray[j]['shorturl']) or dot notation (i.e. replacementArray[j].shorturl). If you use array syntax then the property needs to be in a string literal (unless you create a variable to represent the field - e.g. var shorturl = 'shorturl';).
var replacementArray = [];
function insert(arr, url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
//utilize the function declared above
insert(replacementArray ,"tuto.com", "xfm1");
insert(replacementArray, "youtube.com", "xfm2");
insert(replacementArray, "google.com", "xfm3");
var chaine = "xfm1"; //this is an example
var url; //declare url here so it won't be undefined if no url is found in the array
for (var j = 0; j < replacementArray.length; j++) {
if (replacementArray[j]['shorturl'] == chaine) {
//need to reference replacementArray[j] instead of replacementArray['url']
url = replacementArray[j]['url'];
}
}
console.log('url: ',url);
Consider using Array.prototype.find() or a similar functional-style method (e.g. filter() if you wanted to find multiple values) to determine the site with the matching shorturl value. That way you don't have to worry about creating and incrementing the iterator variable (i.e. j) and using it to reference elements in the array. For more information, try these exercises about functional programming in JS.
var replacementArray = [];
function insert(arr, url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
//utilize the function declared above
insert(replacementArray ,"tuto.com", "xfm1");
insert(replacementArray, "youtube.com", "xfm2");
insert(replacementArray, "google.com", "xfm3");
var chaine = "xfm1"; //this is an example
var foundSite = replacementArray.find(function(site) {
return (site.shorturl == chaine);
});
if (foundSite) { //if we did find a matching site
var url = foundSite.url;
console.log('url: ',url);
}

Try this in your 'for' loop:
if(replacementArray[j].shorturl == chaine){
// Do stuff here...
}
With [shorturl], you are accessing a property name based on the value of shorturl, which is not defined.

Related

Iterating over and comparing properties of two arrays of objects

I have set up a HBS helper which takes in two arrays of objects (users privileges). What I want to do is compare them and inject back into the template the privileges the user does and doesn't have.
Presently I can compare the names of the privileges with the following code:
hbs.registerHelper('selected', function(option, value){
var i;
var j;
var privName;
var userPriv;
var privObj = new Object();
var privArray = [];
for(i in option){
console.log('each ' + JSON.stringify(option[i]));
privName = option[i].privname;
for (y in value){
if(privName == value[y].privname){
userPriv = value[y].privname;
console.log('user has the following privileges', value[y].privname);
privObj = new Object();
privObj.name = userpriv;
privObj.id = value[y]._id;
privObj.state = 'selected';
privArray.push(privObj);
} else if (privName != value[y].privname){
console.log('user doesnt have priv ', privName);
privObj = new Object();
privObj.name = option[i].privname;
privObj.id = option[i].id;
privObj.state = '';
privArray.push(privObj);
}
}
}
console.log('privileges array ', privArray);
return privArray;
});
This works OK when the user only has one privilege, however when the user has more than one, for example two privileges, it returns the privileges twice. If the user has 3, thrice and so on. I know this is because the array is looping again because their are 2, 3 etc in the .length. However I can't seem to find an adequate solution.
Any help?
P.S. it would be nice if the Array.includes() method allowed you to search object properties.
The problem creating new objects the way you did is that for each property you add to your privilege-entity you will have to return to that function and set that property as well. You can instead just add/alter the state property of the existing objects:
hbs.registerHelper('selected', function(option, value) {
var names = option.map(function(opt) {
return opt.privname;
});
value.forEach(function(val) {
val.state = names.indexOf(val.privname) >= 0 ? 'selected' : '';
});
return value;
});
Basically:
The variable names is being mapped to be an array only with the privnames. You can check by using console.log(names).
The Array.forEach() function is helpful in this case because you just need to iterate over each object inside value and set its state-property.
To check if the privname exists, you just need to check the index in the previous names-mapped-array. For such a simple thing I used ternary operator (?:).
Finally, you return value, which is the array containing the objects you had updated.

How to extract a single value from an array

I am very new to JavaScript so forgive me if this is a dumb question:
I have this Ajax call:
$.ajax({
type: 'GET',
url: 'product_prices/' + value,
success: function (data) {
console.log('success', data)
}
});
The value "data" produces an array:
success [{"price":"120.00"}]
What I need, is to extract the value of price (the 120) and use it later in an addition.
How do I get this value out?
You can do:
var price = data[0]['price'];
or:
var price = data[0].price;
Either of these work like this: you are accessing the first value in your array named data, and then the field in that value named "price". Assigning it to a variable isn't necessary.
However, you would probably want to do this inside a loop, iterating over all values of data so that, in the case the first element of data isn't what you want, you can still catch it. For example:
data.forEach(function(i) {
console.log(data[i].price);
//do stuff with the value here
});
data has an array of objects with a price property. Access the first object in the array and parse it's price as a number:
parseFloat(data[0].price);
Test it,
You must parse JSON string before using it!
var data = JSON.parse('[{"price":"120.00"}]');
var Price = data[0].price; // 120.00
//OR IF it's Single And not Array
var Price = data.price; // 120.00
Since your response is an array, access the first position, and then access the object property:
data[0].price; //"120.00"
var result = {},
sum = 0;
$.ajax({
type: 'GET',
url: 'product_prices/' + value,
success: function (data) {
result = data[0];
}
});
sum = parseFloat(result.price) + 2.25;

JSON Object javascript, how to get value not key

I have an JSON object in javascript
"urls": {"url": "http://www.google.co.uk"}
I want to be able to get the actual URL google.co.uk, not the text 'url'.
I also have a variable called date.
I want to create a New object that holds the url value as the key and set the value to the date '20/10/2013' for example.
"newObject": {"http://www.google.co.uk": "20/10/2013"}
Im sure this is possible however I am not so good with json objects and i welcome any help.
IMHO, you should create a readable array like this
var myArray = [
{ url: "http://www.google.co.uk", date: "20/10/2013"},
{ url: "http://www.google.com", date: "20/10/2014" }
]
then you can parse all elements using a for loop for each object in the array.
var myObject;
var url, date;
for(var k = 0; k < myArray.length; k++)
myObject = myArray[k];
url = myObject.url;
date = myObject.date;
}
If you need speed you can use a Memoization Pattern or create hashes to get O(1) queries.
To get the URL, you just have yo do :
var myURL = urls.url;
Then to get the date :
var myDate = newObject[myURL];

access javascript array element by JSON object key

I have an array that looks like this
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}]
I would like to be able to access the Count property of a particular object via the Zip property so that I can increment the count when I get another zip that matches. I was hoping something like this but it's not quite right (This would be in a loop)
Zips[rows[i].Zipcode].Count
I know that's not right and am hoping that there is a solution without looping through the result set every time?
Thanks
I know that's not right and am hoping that there is a solution without
looping through the result set every time?
No, you're gonna have to loop and find the appropriate value which meets your criteria. Alternatively you could use the filter method:
var filteredZips = Zips.filter(function(element) {
return element.Zip == 92880;
});
if (filteredZips.length > 0) {
// we have found a corresponding element
var count = filteredZips[0].count;
}
If you had designed your object in a different manner:
var zips = {"92880": 1, "91710": 3, "92672": 0 };
then you could have directly accessed the Count:
var count = zips["92880"];
In the current form, you can not access an element by its ZIP-code without a loop.
You could transform your array to an object of this form:
var Zips = { 92880: 1, 91710: 3 }; // etc.
Then you can access it by
Zips[rows[i].Zipcode]
To transform from array to object you could use this
var ZipsObj = {};
for( var i=Zips.length; i--; ) {
ZipsObj[ Zips[i].Zip ] = Zips[i].Count;
}
Couple of mistakes in your code.
Your array is collection of objects
You can access objects with their property name and not property value i.e Zips[0]['Zip'] is correct, or by object notation Zips[0].Zip.
If you want to find the value you have to loop
If you want to keep the format of the array Zips and its elements
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}];
var MappedZips = {}; // first of all build hash by Zip
for (var i = 0; i < Zips.length; i++) {
MappedZips[Zips[i].Zip] = Zips[i];
}
MappedZips is {"92880": {Zip: 92880, Count:1}, "91710": {Zip:91710, Count:3}, "92672": {Zip:92672, Count:0}}
// then you can get Count by O(1)
alert(MappedZips[92880].Count);
// or can change data by O(1)
MappedZips[92880].Count++;
alert(MappedZips[92880].Count);
jsFiddle example
function getZip(zips, zipNumber) {
var answer = null;
zips.forEach(function(zip){
if (zip.Zip === zipNumber) answer = zip;
});
return answer;
}
This function returns the zip object with the Zip property equal to zipNumber, or null if none exists.
did you try this?
Zips[i].Zip.Count

Jquery post a Array

I am having a Array which is generated by my Javascript in run time.
once that array is full with all the values I want to send it using POST to the server.
How can I do that ...
Pseudo code:
for(i=0;i<result.data.length;i++)
{
result.data[i].id
}
$.post("receiver.php", { xxxxx }, function(data){ console.log(data);});
How can I get that xxxx updated in the post
I checked the documentation in jquery but they are expecting to give all the values in POST.I do not want to do that.
Also, I want to send post only once so that traffic will be less.
EDIT
You can use join() to get all your array values converted to a string, using some char to separate it.
EDIT 2: As Kumar said he was using 2 arrays
var idsArray;
var namesArray;
for(i=0;i<result.data.length;i++)
{
idsArray[] = result.data[i].id;
namesArray[] = result.data[i].name;
}
var ids = idsArray.join(",");
var names = namesArray.join(",");
$.post("receiver.php", { ids:ids, names:names }, function(data){ console.log(data);});
similar to iBlue's comment, You can just send an object with post; you don't have to define the object in the post function, { } are simply the delimiters to define objects, which are similar to PHP associative arrays:
$.post('reciever.php', myData, function(data){ /*callback*/ });
The only thing is that you setup myData as an object like follows:
myData = {
0: 'info',
1: 'info'
}
//or even something like this
myData = {
someProp: 'info',
someProp2: {
anotherProp: 'moreInfo'
}
}
you can also use non-numerical indexes with objects, and easily add properties:
myData[2] = 'info';
or you can loop through it, just in a slightly different way:
for(i in myData){
myData[i]; //Do something with myArr[i]
}
the for in loop will also loop through non-numerical properties. And you can still get the length of myData by
myData.length;
EDIT:
Instead of sending a string:
IDs = {}
Names = {}
for(var i = 0; i < result.data.length; i++){
IDs[i] = result.data[i].id;
Names[i] = result.data[i].name;
}
$.post('reciever.php', {IDs: IDs, Names: Names}, function(data){});
In the PHP file you would access them like so
$_POST['IDs'][0] = "some id";
$_POST['Names'][0] = "some name";
EDIT:
Actaully I think the indexes are sent as strings, so might have to do
$_POST['IDs']['0']
Not sure, but it seems like you want to do this:
var sendObj = {};
for (var i=0; i<result.data.length; i++) {
var id = result.data[i].id,
name = result.data[i].name; // or some similiar computation
sendObj[name] = id;
}
$.post("receiver.php", sendObj, function(data){ console.log(data);});
This will send the result.data as name=id-value-pairs.

Categories

Resources