簡體   English   中英

JS,JSON:如何獲得符合2個條件的n個頭項?

[英]JS, JSON: How to get the n first items respecting 2 conditions?

給定的數據如下

var people = [ 
{ 'myKey': 'A', 'status': 0, score: 1.5 },
{ 'myKey': 'C', 'status': 1, score: 2.0 },
{ 'myKey': 'D', 'status': 0, score: 0.2 },
{ 'myKey': 'E', 'status': 1, score: 1.0 },
{ 'myKey': 'F', 'status': 0, score: 0.4 },
{ 'myKey': 'G', 'status': 1, score: 3.0 },
];

如何獲得所有帶有'status':1物品'status':1這樣

var people2= [ 
{ 'myKey': 'C', 'status': 1, score: 2.0 },
{ 'myKey': 'E', 'status': 1, score: 1.0 },
{ 'myKey': 'G', 'status': 1, score: 3.0 },
];

編輯:我的最終目的是使n = 2項具有'status':1的升序,例如:

var people3= [ 
{ 'myKey': 'E', 'status': 1, score: 1.0 },
{ 'myKey': 'C', 'status': 1, score: 2.0 },
{ 'myKey': 'G', 'status': 1, score: 3.0 },
]; 

我的方法是將var people所有'status':1轉換為people2 (這是我在這里要查詢的代碼),通過fn來對人people2進行升序排序( people3 ),然后再通過一個fn來選擇'myKey': n=2第一項的值。 所以我得到

var people4 = [ 'E', 'C' ];
function getMyKeys(top) {    
   var result = people.filter(function (item) {
          return item["status"] === 1; //only status=1
       })
       .sort(function (a, b) {
          return a["score"] - b["score"]; //sort 
       })
       .slice(0, top) //top n
       .map(function (item) {
          return item["myKey"]; //return "myKey" property only, if needed.
       });
   }

現場演示

使用新的filter方法有條件地減少數組中的項目集。 一旦減少,就可以通過將比較函數傳遞給Array.sort()對項目進行排序

var people = [ 
{ 'myKey': 'A', 'status': 0, score: 1.5 },
{ 'myKey': 'C', 'status': 1, score: 2.0 },
{ 'myKey': 'D', 'status': 0, score: 0.2 },
{ 'myKey': 'E', 'status': 1, score: 1.0 },
{ 'myKey': 'F', 'status': 0, score: 0.4 },
{ 'myKey': 'G', 'status': 1, score: 3.0 },
];

    var selected = people.filter(function(e){
        return e.status == 1;
    });

    selected.sort(function(a,b){
       if(a.score < b.score){return -1;}
       if(a.score > b.score){ return 1;}
       return 0;
    });

如果必須支持較舊的瀏覽器,則可能需要在瀏覽器中構建.filter方法。 有關MDN的文檔包含.filter的本機實現,可以將其添加到瀏覽器中。

工作示例 http://jsfiddle.net/5zt3A/

您必須根據狀態進行過濾,然后按分數排序,然后僅映射myKey

var people = [ 
{ 'myKey': 'A', 'status': 0, score: 1.5 },
{ 'myKey': 'C', 'status': 1, score: 2.0 },
{ 'myKey': 'D', 'status': 0, score: 0.2 },
{ 'myKey': 'E', 'status': 1, score: 1.0 },
{ 'myKey': 'F', 'status': 0, score: 0.4 },
{ 'myKey': 'G', 'status': 1, score: 3.0 },
];

var result = people.filter(function(i) {
    return i.status == 1;
    })
    .sort(function (a, b) {
        if (a.score == b.score) return 0;
        if (a.score > b.score) return 1;
        return -1;
    }).map(function(i) {
        return i.myKey;
    });

http://jsfiddle.net/GrYuK/1/

提出了另一組答案,我准備了一個鏈接 ,您可以查看該鏈接以獲取更多詳細信息。

  (function getPeopleStatus (person){
    for(var ctr = 0; ctr< person.length; ctr++){

    if(person[ctr].status === 1){
        selection.push(person[ctr]);
    }

}
    selection.sort()
  })(people);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM