属性に基づいてオブジェクト配列をフィルタリングするにはどうすればいいですか? 質問する

属性に基づいてオブジェクト配列をフィルタリングするにはどうすればいいですか? 質問する

不動産ホームオブジェクトの次の 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;

私がやりたいのは、オブジェクトに対してフィルターを実行して、「ホーム」オブジェクトのサブセットを返すことです。

たとえばprice、、、、sqftに基づいてフィルタリングできるようにしたいとします。num_of_bedsnum_of_baths

以下の疑似コードのようなことを JavaScript で実行するにはどうすればよいですか?

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

注意: 構文は上記のとおりである必要はありません。これは単なる例です。

ベストアンサー1

あなたはArray.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);

この方法は新しいECMAScript 第 5 版標準であり、ほとんどすべての最新ブラウザで見つかります。

IE の場合、互換性のために次のメソッドを含めることができます。

if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun /*, thisp*/) {
    var len = this.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
      if (i in this) {
        var val = this[i];
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }
    return res;
  };
}

おすすめ記事