搜尋

首頁  >  問答  >  主體

根據屬性過濾物件數組:指南

我有以下房地產家庭物件的 JavaScript 陣列:

var json = {
    'homes': [{
            "home_id": "1",
            "price": "925",
            "sqft": "1100",
            "num_of_beds": "2",
            "num_of_baths": "2.0",
        }, {
            "home_id": "2",
            "price": "1425",
            "sqft": "1900",
            "num_of_beds": "4",
            "num_of_baths": "2.5",
        },
        // ... (more homes) ...     
    ]
}

var xmlhttp = eval('(' + json + ')');
homes = xmlhttp.homes;

我想做的是能夠對物件執行篩選器以傳回「home」物件的子集。

例如,我希望能夠基於以下內容進行篩選:pricesqftnum_of_bedsnum_of_baths

如何在 JavaScript 中執行類似下面的偽代碼的操作:

var newArray = homes.filter(
    price <= 1000 & 
    sqft >= 500 & 
    num_of_beds >=2 & 
    num_of_baths >= 2.5 );

請注意,語法不必與上面完全相同。這只是一個例子。

P粉087951442P粉087951442463 天前786

全部回覆(2)我來回復

  • P粉366946380

    P粉3669463802023-10-10 10:39:56

    我很驚訝沒有人發布一行回應:

    const filteredHomes = json.homes.filter(x => x.price <= 1000 && x.sqft >= 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5);

    ...只是為了讓您可以更輕鬆地閱讀:

    const filteredHomes = json.homes.filter( x => 
      x.price <= 1000 && 
      x.sqft >= 500 && 
      x.num_of_beds >=2 && 
      x.num_of_baths >= 2.5
    );

    回覆
    0
  • P粉315680565

    P粉3156805652023-10-10 00:41:14

    您可以使用陣列.prototype.filter方法:

    var newArray = homes.filter(function (el) {
      return el.price <= 1000 &&
             el.sqft >= 500 &&
             el.num_of_beds >=2 &&
             el.num_of_baths >= 2.5;
    });

    實例:

    var obj = {
        'homes': [{
                "home_id": "1",
                "price": "925",
                "sqft": "1100",
                "num_of_beds": "2",
                "num_of_baths": "2.0",
            }, {
                "home_id": "2",
                "price": "1425",
                "sqft": "1900",
                "num_of_beds": "4",
                "num_of_baths": "2.5",
            },
            // ... (more homes) ...     
        ]
    };
    // (Note that because `price` and such are given as strings in your object,
    // the below relies on the fact that <= and >= with a string and number
    // will coerce the string to a number before comparing.)
    var newArray = obj.homes.filter(function (el) {
      return el.price <= 1000 &&
             el.sqft >= 500 &&
             el.num_of_beds >= 2 &&
             el.num_of_baths >= 1.5; // Changed this so a home would match
    });
    console.log(newArray);

    回覆
    0
  • 取消回覆