过去几天我一直在自学一些基本的 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/