我有以下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 );

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


当前回答

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请调查一下。

其他回答

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

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

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

然而,由于这个问题已经成为一个流行的重复目标,我应该提到,如果您正在寻找满足条件的单个元素,您不需要过滤器,而是可以使用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 }

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

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

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

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

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

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

希望对大家有用!