使用值内的值从JSON对象获取数据

时间:2016-09-21 09:26:05

标签: javascript jquery json object

我的JSON如下:

{
    "sales": [{
        "manager": "alberic",
        "surgeon": "Dr Barry Biggins",
        "amount": "300",
        "country": "USA",
        "percent-seller": "30",
        "antiquity": "June 2017",
        "date": "6"
    }, {
        "manager": "support",
        "surgeon": "Dr Barry Biggins",
        "amount": "300",
        "country": "UK",
        "percent-seller": "20",
        "antiquity": "June 2017",
        "date": "2"
    }, {
        ...
    }]
}

我想从sales manager = "support"date = "2"中检索{{1}}对象。我如何在jQuery中解决这个问题?

谢谢!

3 个答案:

答案 0 :(得分:2)

只需你可以使用filter()方法并使用你的条件,如果条件变为true,则返回元素,否则忽略元素。

data=    {"sales": [{
          "manager": "alberic",
          "surgeon": "Dr Barry Biggins",
          "amount": "300",
          "country": "USA",
          "percent-seller": "30",
          "antiquity": "June 2017",
          "date": "6"
        }, {
          "manager": "support",
          "surgeon": "Dr Barry Biggins",
          "amount": "300",
          "country": "UK",
          "percent-seller": "20",
          "antiquity": "June 2017",
          "date": "2"
        },
       ]
      };


var matchedElements = data.sales.filter(function(element) {
   return (element.manager == 'support' && element.date == '2');
});
                   
console.log(matchedElements);
                    
//if you want to access  surgeon of first element of matchedElements
                    
console.log(matchedElements[0].surgeon);

          
//if you want to access  surgeon of all elements in matchedElements
for(i in matchedElements)           
{
console.log(matchedElements[i].surgeon);
}

答案 1 :(得分:1)

filter sales数组。

如果您想支持旧浏览器,请务必添加上述链接中的polyfill。

var matchingSales = jsonData.sales.filter(function(sale) {
   return sale.manager == 'support' && sale.date == '2';
});

答案 2 :(得分:1)



var data = {
  "sales": [{
    "manager": "alberic",
    "surgeon": "Dr Barry Biggins",
    "amount": "300",
    "country": "USA",
    "percent-seller": "30",
    "antiquity": "June 2017",
    "date": "6"
  }, {
    "manager": "support",
    "surgeon": "Dr Barry Biggins",
    "amount": "300",
    "country": "UK",
    "percent-seller": "20",
    "antiquity": "June 2017",
    "date": "2"
  }]
};


$.each(data.sales, function(i, v) {

  if (v.manager == 'support' && v.date == '2') {
    console.log(v.manager)
    console.log(v.surgeon)
    console.log(v.amount)
  }

})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

使用.each()

对它们进行迭代
相关问题