我有一个像这样的对象:
{
"data": [
{
"id": "1234",
"is_deleted": false,
"name": "Sarah"
},
{
"id": "3520",
"is_deleted": true,
"name": "Bobby"
},
{
"id": "3520",
"is_deleted": true,
"name": "Sartah"
}
]
}
反应代码
import React from 'react';
import { Input } from 'antd';
import { connect } from 'dva';
const Search = Input.Search;
@connect(({ rule, loading }) => ({
rule,
loading: loading.models.rule,
}))
export default class SearchBox extends React.Component {
constructor(props) {
super(props)
this.state = {
isListLoaded: false,
resultArr: {}
}
}
performSearch(value) {
for( var i = this.props.rule.data.list.length; i--; ) {
for (var key in this.props.rule.data.list[i]) {
this.setState({resultArr: this.state.resultArr.push(i)});
}
}
}
componentDidMount() {
if (!this.state.isListLoaded) {
const { dispatch } = this.props;
dispatch({
type: 'rule/fetch'
});
this.setState({ isListLoaded: true });
}
}
render() {
return (
<div>
<Search
placeholder="Search..."
onChange={(event) => this.performSearch(event.target.value)}
style={{ width: "250px", "margin-left": "20px"}}
/>
</div>
);
}
}
我的目标非常简单:我想搜索这个对象,并且 返回包含关键字的整个数组。
示例:如果我搜索&#34; Sar&#34;,我应该得到2个对象:
{
"id": "1234",
"is_deleted": false,
"name": "Sarah"
},
{
"id": "3520",
"is_deleted": true,
"name": "Sartah"
}
问题是,我在尝试此代码时遇到错误。我在SO上搜索了此问题的先前解决方案,但我只能找到只返回一个元素的示例。我想要的是,所有包含 ANY 属性中的关键字的结果(在此示例中,我返回2个元素,而不只是一个)< / p>
有什么想法吗?
答案 0 :(得分:1)
const { data } = {
"data": [
{
"id": "1234",
"is_deleted": false,
"name": "Sarah"
},
{
"id": "3520",
"is_deleted": true,
"name": "Bobby"
},
{
"id": "3520",
"is_deleted": true,
"name": "Sartah"
}
]
};
const keyword = "Sar";
const filtered = data.filter(entry => Object.values(entry).some(val => typeof val === "string" && val.includes(keyword)));
console.log(filtered);
它使用以下标准过滤entries
数据数组:至少有一个条目的值必须包含给定的关键字。
由于IE尚不支持Object.values()
和String.prototype.includes()
,您可以使用以下内容:
const containsKeyword = val => typeof val === "string" && val.indexOf(keyword) !== -1;
const filtered = data.filter(entry => Object.keys(entry).map(key => entry[key]).some(containsKeyword));
或polyfill这些ES6功能,请参阅更多here。
要使keyword
查询字符串不敏感,可以使用RegExp:
const re = new RegExp(keyword, 'i');
const filtered = data.filter(entry => Object.values(entry).some(val => typeof val === "string" && val.match(re)));
答案 1 :(得分:0)
而不是循环遍历数组,只需使用javascript的过滤方法
performSearch(value) {
const unfilteredData = this.props.rule.data.list;
const filteredDate = unfilteredData.filter((val) => {
return val.name.indexOf(val) !== -1;
});
this.setState({
resultArr: filteredDate,
})
}
答案 2 :(得分:0)
performSearch(value) {
let filteredData = this.props.rule.data.list.filter(item => {
let isFiltered = false;
for(let key in item){
if(item[key].includes(value)){
isFiltered = true;
}
}
return isFiltered;
})
this.setState({resultArr: filteredData});
}