0

I have an array like this:

"links": [{
  "url": "http:...",
  "title": "3"
}, {
  "url": "http://facebook.com/pages/",
  "title": "2"
},{
  "url": "http://...",
  "title": "2"
}],

I want to find out of the array has the word 'facebook' and if so to take the specific url with the word and use it. I tried this code but it doesn't work.

var arraylinks = mdata.links;
if (arraylinks[i].url === "facebook") {
    for (var i = 0; i < arraylinks.length; i++) {
        var klink = $("<a>").attr("href", arraylinks[i].url).attr('target', '_blank').addClass("icon-library");
    }
}

I would appreciate your help. thank you

1
  • well, facebook is only part of the full url, you could test it with /facebook/i.test(arraylinks[i].url) or something similar to make sure it actually contains the word facebook Commented Jan 7, 2017 at 23:39

4 Answers 4

6

You can use Array.filter, Regex to filter your list.

var array = [{
  "url": "http:...",
  "title": "3"
}, {
  "url": "http://facebook.com/pages/",
  "title": "2"
},{
  "url": "http://...",
  "title": "2"
}];

var filtered = array.filter(function (obj) {
  return /facebook/i.test(obj.url);
})

console.log(filtered[0]);

Sign up to request clarification or add additional context in comments.

Comments

1

You could use indexOf on the urls to keep it basic.

var arraylinks = mdata.links;
var wordToFind = "facebook"
if (arraylinks[i].url && arraylinks[i].url.toLowerCase().indexOf(wordToFind) >= 0 ) {
  for (var i = 0; i < arraylinks.length; i++) {
    var klink = $("<a>").attr("href", arraylinks[i].url)
    .attr('target', '_blank').addClass("icon-library");
  }
}

5 Comments

True, you did, however the only right answer I see is the one from BrunoLM (though yours is the second best at the moment ;)).
Agreed, but i figured it's better to update my answer rather than removing it ;)
You're right, didn't realize the lines were reversed. Thanks @Icepickle
Your last edit is incorrect (run it in jsfiddle or something), link would be 0, 1, 2 (the property name of the array) (see here)
Fixed it again!
0

so you could do this:

var arraylinks = mdata.links;
for (var i = 0; i < arraylinks.length; i++) {
    if (arraylinks[i].url.indexOf("facebook") != -1) {    
        var klink = $("<a>").attr("href", arraylinks[i].url).attr('target', '_blank').addClass("icon-library");
        // do something with klink here
    }
}

I also think the for loop needs to be outside of the if statement

Comments

0

You can use this

fbLink = links.find(function(el){
   return el.url.indexOf('facebook') >= 0 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.