我有以下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 state.contactList = [{
    name: 'jane',
    email: 'jane@gmail.com'
  },{},{},...]

const fileredArray = state.contactsList.filter((contactItem) => {
  const regex = new RegExp(`${action.payload}`, 'gi');
  return contactItem.nameProperty.match(regex) || 
    contactItem.emailProperty.match(regex);
});


// contactList: all the contacts stored in state
// action.payload: whatever typed in search field

其他回答

这个问题是在考虑多种结果的情况下提出的,在这种情况下,过滤器是可行的方法,正如这里的其他回答者已经指出的那样。

然而,由于这个问题已经成为一个流行的重复目标,我应该提到,如果您正在寻找满足条件的单个元素,您不需要过滤器,而是可以使用find。它以同样的方式工作,但它只是返回第一个匹配的元素,如果没有元素匹配则返回undefined,而不是返回一个匹配数组:

const data = [
  { id: 1, value: 10 },
  { id: 2, value: 20 },
  { id: 3, value: 30 }
]

console.log(data.filter(o => o.value > 15))
// Output: [{ id: 2, value: 20 }, { id: 3, value: 30 }]

console.log(data.find(o => o.value > 15))
// Output: { id: 2, value: 20 }

console.log(data.filter(o => o.value > 100))
// Output: []

console.log(data.find(o => o.value > 100))
// Output: undefined

// `find` is often useful to find an element by some kind of ID:
console.log(data.find(o => o.id === 3))
// Output: { id: 3, value: 30 }

我更喜欢下划线框架。它提出了许多有用的对象操作。 你的任务:

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

可以像这样覆盖:

var newArray = _.filter (homes, function(home) {
    return home.price<=1000 && sqft>=500 && num_of_beds>=2 && 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",
    },
]

你可以很容易地做到这一点-可能有很多实现可供你选择,但这是我的基本想法(可能有一些格式,你可以用jQuery迭代一个对象,我只是现在想不起来):

function filter(collection, predicate)
{
    var result = new Array();
    var length = collection.length;

    for(var j = 0; j < length; j++)
    {
        if(predicate(collection[j]) == true)
        {
             result.push(collection[j]);
        }
    }

    return result;
}

然后你可以像这样调用这个函数:

filter(json, function(element)
{
    if(element.price <= 1000 && element.sqft >= 500 && element.num_of_beds > 2 && element.num_of_baths > 2.5)
        return true;

    return false;
});

这样,您可以根据定义的任何谓词调用筛选器,甚至可以使用更小的筛选器进行多次筛选。

var filterHome = homes.filter(home =>
  return (home.price <= 999 &&
         home.num_of_baths >= 2.5 &&
         home.num_of_beds >=2 &&
         home.sqft >= 998));
console.log(filterHome);

你可以用这个函数。更多的细节可以在这里找到,因为我们过滤的数据基于你有条件返回真或假,它将收集数据在不同的数组,所以你的实际数组将不会被修改。

@JGreig请调查一下。