nourhein chaieb nourhein chaieb - 26 days ago 10
Javascript Question

how do i get values from multidimensionnal table in 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?

Answer

Read over these corrections/suggestions:

  1. As others have mentioned, you should create an array of objects, instead of an object with arrays
  2. 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);

  1. 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);
}

Comments