迭代Json数组而没有键

时间:2017-03-09 10:57:03

标签: javascript arrays json loops

首先,这个问题可能已经被问了好几次,但我找到的每个帖子都没有帮助我。如果可以在下面改写我的功能,我将不胜感激。

我有以下数组与Json对象。

目标是获取“网址”值。现在我从该数组获得每个值。

a = [{
  "result": [{
      "name": [
        "name"
      ],
      "url": [
        "www.bar.com"
      ]
    },
    {
      "name": [
        "name 2"
      ],
      "url": [
        "www.bar.org"
      ]
    },
    {
      "name": [
        "name 1"
      ],
      "url": [
        "www.bar.biz"
      ]
    },
    {
      "name": [
        "name 3"
      ],
      "url": [
        "www.bar.jp"
      ]
    }
  ]
}];
document.getElementById("foo").innerHTML = "How to explicitly get the url value?'";
loopThrough(a);

function loopThrough(obj) {
  for (var key in obj) {
    // skip loop if the property is from prototype
    if (!obj.hasOwnProperty(key)) continue;

    if (typeof obj[key] !== 'object') {
      console.log(obj[key]);
    } else {
      loopThrough(obj[key]);
    }
  }
}
<div id="foo">
</div>

如何访问此数组中的每个“url”元素?

也许还有比这更聪明的解决方案。

提前谢谢。

2 个答案:

答案 0 :(得分:2)

a = [{
  "result": [{
      "name": [
        "name"
      ],
      "url": [
        "www.bar.com"
      ]
    },
    {
      "name": [
        "name 2"
      ],
      "url": [
        "www.bar.org"
      ]
    },
    {
      "name": [
        "name 1"
      ],
      "url": [
        "www.bar.biz"
      ]
    },
    {
      "name": [
        "name 3"
      ],
      "url": [
        "www.bar.jp"
      ]
    }
  ]
}];
loopThrough(a);

// Uses ES6 syntax
function loopThrough(obj) {
  obj[0].result.forEach(r => console.log(r.url[0]));
}

答案 1 :(得分:1)

亲自尝试。

&#13;
&#13;
var a = [{
  "result": [{
      "name": [
        "name"
      ],
      "url": [
        "www.bar.com"
      ]
    },
    {
      "name": [
        "name 2"
      ],
      "url": [
        "www.bar.org"
      ]
    },
    {
      "name": [
        "name 1"
      ],
      "url": [
        "www.bar.biz"
      ]
    },
    {
      "name": [
        "name 3"
      ],
      "url": [
        "www.bar.jp"
      ]
    }
  ]
}];

var urls=a[0].result.reduce(function(urls,it){
  return urls.concat(it.url);
},[]);
console.log(urls);
&#13;
&#13;
&#13;