1

I have an array with several items inside and one of them is location .some of those locations are empty inside with no value. I want to take every one of those empty locations and perform a function . Does any know how to do that?

The array might look like this:

array=[{user:a,user_id:b,date:c,profile_img:d,text:e,contentString:f,url:g,location:""},    
{user:a,user_id:b,date:c,profile_img:d,text:e,contentString:f,url:g,location:""}];
anjel
  • 1,355
  • 4
  • 23
  • 35
  • Can you elaborate your question with a code sample of what you have and what you want to achieve? – user1071979 Aug 18 '12 at 20:54
  • [forEach](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach) – Andreas Aug 18 '12 at 20:56
  • We need to see the actual data in your array to know what code to advise. Your words to not adequately describe the data structure. – jfriend00 Aug 18 '12 at 21:01

3 Answers3

0

A simple for loop should work:

for (var i = 0; i < array.length; i++) {
    if (array[i].location.length == 0) {
        //Do something with array[i]
    }
}
Janis Elsts
  • 754
  • 3
  • 11
0

While you could write a loop, its much easier to use Underscore.js, which has an awesome filter function.

Just write a test to return users with an empty location.

var allUsers = [{
    user: "user-with-location",
    user_id: "b",
    date: "c",
    profile_img: "d",
    text: "e",
    contentString: "f",
    url: "g",
    location: "asdf"
}, {
    user: "user-without-location",
    user_id: "b",
    date: "c",
    profile_img: "d",
    text: "e",
    contentString: "f",
    url: "g",
    location: ""
}];

var usersWithoutLocation = _.filter(allUsers, function(user) {
    return user.location === "";
});
Luqmaan
  • 2,052
  • 27
  • 34
0

And as a tip, you can simplify the value check.

for (var i = 0; i < array.length; i++) {
  if (!array[i].location) {
    //Do something with array[i]
  }
}
Community
  • 1
  • 1
techn1cs
  • 46
  • 3