如何通过条件提取json元素?

时间:2016-02-09 16:03:17

标签: javascript json

我有一个JSON对象如下:

  "links" : [ {
    "rel" : "first",
    "href" : "http://localhost:8080/first"
  }, {
    "rel" : "self",
    "href" : "http://localhost:8080/self"
  }, {
    "rel" : "next",
    "href" : "http://localhost:8080/next"
  }];

现在我想将href网址rel = "next"放在哪里。 问题:我怎么能用javascript来搞定这个?

在Java中,我循环遍历数组并创建反HashMap<Rel, Href>,并调用map.get("next");

但这是如何在JS中完成的?

1 个答案:

答案 0 :(得分:1)

这应该适合你。

var safe = {
    "links": [{
        "rel": "first",
        "href": "http://localhost:8080/first"
    }, {
        "rel": "self",
        "href": "http://localhost:8080/self"
    }, {
        "rel": "next",
        "href": "http://localhost:8080/next"
    }]
};

var i,
    l = safe.links.length;

for (i = 0; i < l; i += 1) {
    if (safe.links[i].rel === 'next') {
        console.log(safe.links[i].href);
    }
}