简体   繁体   中英

Javascript what is the best way to filter objects based on a list of strings in an array?

I have the following array which has strings in it

const dict = ['original sound', 'الصوت الأصلي', 'оригинальный звук'];

Now I want to filter it based on the array using object filter

Object.filter = (obj, predicate) =>
    Object.keys(obj)
          .filter( key => predicate(obj[key]) )
          .reduce( (res, key) => (res[key] = obj[key], res), {} );

let filtered = Object.filter(audio, audio =>
  audio.audio.title !== dict
);

To be clear I don't want any music with the titles that match the dict array

Check if the array doesn't include that element:

let filtered = Object.filter(audio, audio =>
   !dict.includes(audio.audio.title)
);

If I understand correctly, you want to filter an array of strings, based on another string array as dictionary, if so, try below

var filtered = ['a', 'b', 'c', 'd'].filter(
  function(e) {
    return this.indexOf(e) < 0;
  },
  ['b', 'd']
);

becarefull of string. includes (anotherString) is NOT working on IE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM