如何获取数组中的每个特定值?

时间:2017-03-29 23:07:02

标签: javascript arrays iteration

我希望能够从以下数组中提取每个'hire_address'值并将其添加到单独的数组中。

var addr =
{  
   "status":"success",
   "data":[  
      {  
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Glasgow",
         "offer_oucu":"ac1",
         "offer_address":"Glasgow"
      },
      {  
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Poole",
         "offer_oucu":"ac1",
         "offer_address":"Poole"
      }
      {  
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Hastings",
         "offer_oucu":"ac1",
         "offer_address":"Hastings"
      }
      {  
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"London",
         "offer_oucu":"ac1",
         "offer_address":"London"
      }
   ]
};

我目前有

var addresses = [];
$.each(addr.data.hire_address, function (index, value) {
addresses.push(value);

但没有运气。有什么建议吗?

感谢您的回复。

我现在有

var addresses = [];
$.each(addr, function (index, value) {
    if (value == "data"){
        addresses.push(value.hire_address);
    }
}
);

但似乎无法让它发挥作用。我需要if声明吗?我添加了这个,因为第一项是'status',如果我尝试添加'hire_address'属性,因为它不存在而遇到错误。

4 个答案:

答案 0 :(得分:0)

$。每个都有两个参数,第一个是数组。你应该传入你想要循环的数组。

第二个参数是在数组中每个项目调用的函数。它存储在value参数中。如果循环遍历数组,则可以访问正确的属性,如下所示:

value.hire_address

http://api.jquery.com/jquery.each/

答案 1 :(得分:0)

使用Array.map

addr.data.map(d => d.hire_address)

答案 2 :(得分:0)

你可以使用Array#map()来做

var addr = {
  "status": "success",
  "data": [{
      "start": "2017-01-26 12:30:00",
      "hire_oucu": "ac2",
      "hire_address": "Glasgow",
      "offer_oucu": "ac1",
      "offer_address": "Glasgow"
    },
    {
      "start": "2017-01-26 12:30:00",
      "hire_oucu": "ac2",
      "hire_address": "Poole",
      "offer_oucu": "ac1",
      "offer_address": "Poole"
    }, {
      "start": "2017-01-26 12:30:00",
      "hire_oucu": "ac2",
      "hire_address": "Hastings",
      "offer_oucu": "ac1",
      "offer_address": "Hastings"
    }, {
      "start": "2017-01-26 12:30:00",
      "hire_oucu": "ac2",
      "hire_address": "London",
      "offer_oucu": "ac1",
      "offer_address": "London"
    }
  ]
};

let myArray = addr.data.map(d => d["hire_address"]);
console.log(myArray);

答案 3 :(得分:0)

修复对象后(请参阅我的评论),您可以在没有jQuery的情况下进行迭代:

var addresses=[];
addr.data.forEach(function(a){
    addresses.push(a.hire_address);
});
alert(addresses);

JavaScript .forEach()数组方法与jQuery的.each()做了类似的工作而没有开销。

或者,对于旧浏览器:

for(var i=0;i<addr.data.length;i++)
    addresses.push(addr.data[i].hire_address);