javascript - 基本的 javascript json 子数组解码

标签 javascript arrays json twitter

过去几天我一直在自学一些基本的 javascript,并使用 google 脚本和 Twitter api,但在一些本来应该很简单的事情上有点脱节!

为了更容易输入,所以我从 twitter api 的返回看起来像这样

[id:1
connections: "NONE"
],

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

我想做的是找出用户 2 是否存在“following”键,但我真的很挣扎!

twitter api 文档显示了一个示例 json

[
  {
    "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"
  }
]

任何人都可以指出我正确的方向吗?我如何查明以下内容是否存在?

谢谢

最佳答案

connections: ["following", "followed_by"] 是一个数组。要检查数组是否包含特殊值,可以使用 indexOf():

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

因此要检查“following”是否在数组中:

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

要计算示例中具有“以下”的对象:

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);

关于javascript - 基本的 javascript json 子数组解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22995188/

相关文章:

arrays - 如何删除 mongoDB 中数组中的数组?

javascript - 操作 JSON 数组数据

javascript - 达到最大高度并且 div 像响应式 overflow-x 一样继续向右移动

javascript - JQuery 鼠标悬停事件的兼容性问题

JavaScript:根据字符串包含的数字对字符串进行排序

java - Gson JSON 最大大小

java - 是否可以在类级别为不同的数据类型配置 Jackson 自定义反序列化器?

javascript - 多文件上传。输入字段的 cloneNode 与 IE

c - 如何使用 toupper() 函数来计算小写和大写用户输入?

python - 如何获取特定标签之前/之前的 n 个索引号?