0

I have been teaching myself some basic javascript the last couple of days and playing with google scripting as well as the twitter api and have come a bit unstuck on something that should probably be quite easy!

For sake of easierness of typing so my return from twitter api looks like this

[id:1
connections: "NONE"
],

[id:2
connections: ["following", "followed_by"]
]

What I am trying to do is find out out if the key 'following' exists for user 2, but I am really struggling!

The twitter api docs show an examples json as

[
  {
    "name": "Taylor Singletary",
    "id_str": "819797",
    "id": 819797,
    "connections": [
      "none"
    ],
    "screen_name": "episod"
  },
  {
    "name": "Twitter API",
    "id_str": "6253282",
    "id": 6253282,
    "connections": [
      "following",
      "followed_by"
    ],
    "screen_name": "twitterapi"
  }
]

Can any point me in the correct direction?, how do I find out if following exists?

Thanks

2
  • Not sure if I understand, you want to check of the second element in array has the value 'following' in connections array? Commented Apr 10, 2014 at 17:54
  • Hi juvian, that is correct, however if it doesnt exist then the array just reads "connections":["followed_by"], is there a way to count the results? Commented Apr 10, 2014 at 17:58

1 Answer 1

2

connections: ["following", "followed_by"] is an array. To check if an array contains a special value you can use indexOf():

var a = [1, 2, "three", 44];
a.indexOf(1); // 0
a.indexOf(2); // 1
a.indexOf("three"); // 2
a.indexOf(22); // -1

So to check if "following" is in the array:

if (connections.indexOf("following") !== -1) {
  // yeah!
} else {
  // doh!
}

To count the objects in your example which have "following":

var o = [
  {
    "name": "Taylor Singletary",
    "id_str": "819797",
    "id": 819797,
    "connections": [
      "none"
    ],
    "screen_name": "episod"
  },
  {
    "name": "Twitter API",
    "id_str": "6253282",
    "id": 6253282,
    "connections": [
      "following",
      "followed_by"
    ],
  "screen_name": "twitterapi"
  }
];

var withFollowing = o.filter(
  function (i) {
    return i.connections.indexOf("following") !== -1;
  }
);
// filter() returns a new array
// this new array has only the elements for which the function returns true

console.log(withFollowing.lenght);
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome answer, thanks that really helped, kudos for the range of possibilities as well!

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.