0

I have a problem to write this code dynamically.

How can I write testtest function dynamically, if in the future data could have different keys and values?

my json object looks just like this:

data = [
    {
      name: 'John',
      id: 1,
      colour: 'Green',
      pet: 'Dog'
    },
    {
      name: 'Sarah',
      id: 2,
      colour: 'Purple',
      pet: 'Cat'
    },
    {
      name: 'Lindsay',
      id: 3,
      colour: 'Blue',
      pet: 'Lizard'
    },
    {
      name: 'Megan',
      id: 4,
      colour: 'Orange',
      pet: 'Dog'
    }
];

and I have a filtervalue

filterValues = {
    name: '',
    id: '',
    colour: '',
    pet: ''
};

now a function

createFilter(): (data: any, filter: string) => boolean {
    let filterFunction = function(data, filter): boolean {
        let searchTerms = JSON.parse(filter);
        let result = this.testtest(data, searchTerms);
        return result;
    }
    return filterFunction;
}

testtest(data, searchTerms): boolean {
    return data.name.toLowerCase().indexOf(searchTerms.name) !== -1
        && data.id.toString().toLowerCase().indexOf(searchTerms.id) !== -1
        && data.colour.toLowerCase().indexOf(searchTerms.colour) !== -1
        && data.pet.toLowerCase().indexOf(searchTerms.pet) !== -1;
}
4

2 回答 2

0

你可以这样做:

testtest(data, searchTerms): boolean {
var result = false;
for (var property in data) {
if (data.hasOwnProperty(property)) {
     result = ( property.toLowerCase().indexOf(searchTerms[property]) !==-1 )
     if(!result){
       return result;
     }   
}
else {
  return result;
}
}
}
于 2019-05-17T08:08:21.043 回答
0

你可以在 ES6 中使用类似的东西 -

data.filter(obj => Object.keys(obj).some(key => obj[key] == searchText));
于 2019-05-17T08:25:00.360 回答