我有以下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”对象的子集。

例如,我希望能够基于:price、sqft、num_of_beds和num_of_baths进行过滤。

我如何在JavaScript中执行下面的伪代码:

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

注意,语法不必完全像上面那样。这只是一个例子。


当前回答

const y = 'search text';
const a = [{key: "x", "val: "y"},  {key: "d", "val: "z"}]
const data = a.filter(res => {
        return(JSON.stringify(res).toLocaleLowerCase()).match(y.toLocaleLowerCase());
});

其他回答

你可以使用jQuery.grep()自jQuery 1.0:

$.grep(homes, function (h) {
  return h.price <= 1000
    && h.sqft >= 500
    && h.num_of_beds >= 2
    && h.num_of_baths >= 2.5
});

我看到有一种情况没有被覆盖,也许有人会像我一样寻找匹配的情况。情况下,当有人想要过滤属性值,这是字符串或数字使用过滤作为“where matches”条件,让我们说通过城市名称等。换句话说,就像Query:返回ALL homes数组WHERE city = "Chicago"。解决方法很简单:

  const filterByPropertyValue = (cityName) => {
    let filteredItems = homes.filter((item) => item.city === cityName);
    console.log("FILTERED HOMES BY CITY:", filteredItems);
  }

如果你需要通过编程或在HTML中循环/映射数组或通过提供'city'值来触发它(你也可以提供数组,只需要在函数中添加它来重用函数):

            <button
              onClick={() => {
                filterByPropertyValue("Chicago");
              }}
            >
              Chicago Homes Only
            </button>

假设JSON添加了城市属性:

'homes': [{
        "home_id": "1",
        "price": "925",
        "sqft": "1100",
        "num_of_beds": "2",
        "num_of_baths": "2.0",
        "city":"Chicago",
    }, {
        "home_id": "2",
        "price": "1425",
        "sqft": "1900",
        "num_of_beds": "4",
        "num_of_baths": "2.5",
        "city":"Chicago",
    },
    // ... (more homes) ...     
    {
        "home_id": "3-will-be-matched",
        "price": "925",
        "sqft": "1000",
        "num_of_beds": "2",
        "num_of_baths": "2.5",
        "city":"Atlanta",
    },
]

我很惊讶居然没有人发这样的回复:

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
);

你可以尝试使用像jLinq这样的框架——下面是一个使用jLinq的代码示例

var results = jLinq.from(data.users)
.startsWith("first", "a")
.orEndsWith("y")
.orderBy("admin", "age")
.select();

欲了解更多信息,请访问http://www.hugoware.net/projects/jlinq

你可以自己实现一个过滤方法来满足你的需求,下面是如何实现的:

function myfilter(array, test){
    var passedTest =[];
    for (var i = 0; i < array.length; i++) {
       if(test( array[i]))
          passedTest.push(array[i]);
    }

    return passedTest;
}

var passedHomes = myfilter(homes,function(currentHome){
     return ((currentHome.price <= 1000 )&& (currentHome.sqft >= 500 )&&(currentHome.num_of_beds >=2 )&&(currentHome.num_of_baths >= 2.5));
});

希望有帮助!