如何按条件提取 json 元素

How to extract a json element by condition?

本文关键字:json 元素 提取 条件 何按      更新时间:2023-09-26

我有一个JSON对象,如下所示:

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

现在我想获取rel = "next"href网址。问题:我怎样才能用javascript得到这个?

在Java中,我会遍历数组并创建一个逆HashMap<Rel, Href>,调用map.get("next");

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

这应该适合你。

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