如何遍历此对象?

时间:2016-11-24 04:49:08

标签: javascript

我想通过创建function country(state,foods)来遍历此对象 如果状态和食物存在于对象中,它应该返回该州的州名和食物数组。首先,我尝试通过使用for in在函数中传递参数状态来仅迭代状态仍然我没有得到州名,我不知道该怎么办才能得到食物。

var india = [
        {
            "state": "karnataka",
            "capital": "Bengaluru",
            "foods": ["Mysore masala", "Uthhappa", "Bisi Bele Bhaat"]
        },
        {
            "state": "Maharashtra",
            "capital": "Mumbai",
            "foods": ["vada pav", "puranpoli", "Missal pav"]
        },

        {
            "state": "Tamil nadu",
            "capital": "Chennai",
            "foods": ["Medu vada", "aapam", "idli sambhar"]
        },

        {
            "state": "Rajasthan",
            "capital": "Jaipur",
            "foods": ["Ras malai", "Kadka", "Gujia"]

        }
    ];

5 个答案:

答案 0 :(得分:2)

这对于您的用例来说是一个糟糕的数据结构,因此如果您希望经常搜索此数据,您可能会考虑将状态名称作为对象的属性进行O(1)查找而不是O(n)方法迭代这个数组。话虽这么说,在这种情况下可以使用Array.find()来搜索这个现有的结构。

var result = india.find( item => (item.state === this) , searchState);
console.log(result.foods);

答案 1 :(得分:1)

for (var i in india)
{
    alert(india[i].state);
    // do something else with india[i]
}

或者india是一个数组:

for (var i = 0; i < india.length; ++i)
{
    // same thing
}

当搜索数组中是否存在特定数字或字符串时,您可以使用Array.indexOf(),例如:

if (india[i].foods.indexOf('Kadka') >= 0)
{
    alert(india[i].state + " has food Kadka");
}

函数StateHasFood(state, food)可能是这样的:

function StateHasFood(state, food)
{
    for (var i in india)
        if (india[i].state == state)
            return india[i].foods.indexOf(food) >= 0;
    return false;
}

当然,你也可以相对于包含其属性的状态返回对象,包括它的名称和你想要的食物的完整列表:

function StateHasFood(state, food)
{
    for (var i in india)
        if (india[i].state == state)
            if (india[i].foods.indexOf(food) >= 0)
                return india[i];
    return false;
}

答案 2 :(得分:0)

尝试使用forEach()方法进行迭代,并Object.keys获取密钥:值对。不完全理解OP的目标,所以我将添加objArrKey()。此函数获取数组和特定键,并返回与所述键关联的所有值。

var India = [{
  "state": "karnataka",
  "capital": "Bengaluru",
  "foods": [
    "Mysoremasala",
    "Uthhappa",
    "BisiBeleBhaat"
  ]
}, {
  "state": "Maharashtra",
  "capital": "Mumbai",
  "foods": [
    "vadapav",
    "puranpoli",
    "Missalpav"
  ]
}, {
  "state": "Tamilnadu",
  "capital": "Chennai",
  "foods": [
    "Meduvada",
    "aapam",
    "idlisambhar"
  ]
}, {
  "state": "Rajasthan",
  "capital": "Jaipur",
  "foods": [
    "Rasmalai",
    "Kadka",
    "Gujia"
  ]
}]


India.forEach(function(item) {
  Object.keys(item).forEach(function(key) {
    console.log("key:" + key + " value:" + item[key]);
  });
});

function objArrKey(arr, key) {
  return arr.map(function(item) {
    return item[key] || null;
  });
}

console.log(objArrKey(India, ['state']));
console.log(objArrKey(India, ['capital']));
console.log(objArrKey(India, ['foods']));

答案 3 :(得分:0)

因为你刚刚告诉我写一个函数来检查状态和资本是否存在,这是真的然后返回资本。我已经为你写了这个。希望它有所帮助:)

&#13;
&#13;
var india = [
      {
          "state": "karnataka",
          "capital": "Bengaluru",
          "foods": ["Mysore masala", "Uthhappa", "Bisi Bele Bhaat"]
      },
      {
          "state": "Maharashtra",
          "capital": "Mumbai",
          "foods": ["vada pav", "puranpoli", "Missal pav"]
      },

      {
          "state": "Tamil nadu",
          "capital": "Chennai",
          "foods": ["Medu vada", "aapam", "idli sambhar"]
      },

      {
          "state": "Rajasthan",
          "capital": "Jaipur",
          "foods": ["Ras malai", "Kadka", "Gujia"]
      }
  ];

function country(someState , someCapital){
  for (var i in india)
   {
    if(india[i].state === someState && india[i].capital === someCapital){
        return india[i].capital;
    }
  }
}

document.write(country("Tamil nadu", "Chennai"));
&#13;
&#13;
&#13;

答案 4 :(得分:0)

根据您在评论中添加的内容,您真正想要的是一个函数app.controller("myVm", function($scope) { var vm=$scope; vm.DeleteElementFromSession = function(e) { var elem = angular.element(e.currentTarget); vm.id = elem.parent().parent().attr("id"); } }); ,它将返回与指定状态关联的指定属性的值。也就是说,getPropForState(state, prop)会返回一系列食物,getPropForState("Rajasthan", "foods")会返回getPropForState("Rajasthan", "capital")

假设情况属实,可能如下:

&#13;
&#13;
"Jaipur"
&#13;
&#13;
&#13;

请注意,如果状态或指定的其他属性不存在,则该函数将返回// same array as in question, but with line breaks removed // so that it doesn't clutter up my answer var india = [{"state":"karnataka","capital":"Bengaluru","foods":["Mysore masala","Uthhappa","Bisi Bele Bhaat"]},{"state":"Maharashtra","capital":"Mumbai","foods":["vada pav","puranpoli","Missal pav"]},{"state":"Tamil nadu","capital":"Chennai","foods":["Medu vada","aapam","idli sambhar"]},{"state":"Rajasthan","capital":"Jaipur","foods":["Ras malai","Kadka","Gujia"]}]; function getPropForState(state, prop) { var item = india.find(v => v.state === state); if (item) return item[prop]; } console.log(getPropForState("Rajasthan", "foods")); // returns ["Ras malai","Kadka","Gujia"] console.log(getPropForState("Rajasthan", "capital")); // returns "Jaipur" console.log(getPropForState("Maharashtra", "capital")); // returns "Mumbai" console.log(getPropForState("Maharashtra", "missing")); // returns undefined console.log(getPropForState("Queensland", "foods")); // returns undefined