简体   繁体   中英

Underscore where es6/typescript alternative

Is there alternative for underscore method (where)?

I would like to find an array with some properties like here:

_.where(listOfPlays, {author: "Shakespeare", year: 1611});
=> [{title: "Cymbeline", author: "Shakespeare", year: 1611},

You can use Array#filter . You won't be able to use an object but you can use properties directly:

let results = listOfPlays.filter(play => play.author === "Shakespeare" && play.year === 1611);

Alternatively, if you actualy want a replica of _.where :

function where(array, object) {
  let keys = Object.keys(object);
  return array.filter(item => keys.every(key => item[key] === object[key]));
}

where filters objects from array that match every key-value from the object object .

Basic concept of Array.filter, Array.each, and Object.entries

 var plays = [ { title: "world", author: "hello", year: 1611 }, { title: "Cymbeline", author: "Shakespeare", year: 1611 }, { title: "Bacon", author: "Shakespeare", year: 1611 }, { title: "Dance", author: "Shakespeare", year: 1610 } ] const getResults = (plays, filters) => { const entries = Object.entries(filters) return result = plays.filter( play => { return entries.every(([key, value]) => { return play[key] === value }) }) } var testOne = getResults(plays, { author: "Shakespeare", year: 1611 }) var testTwo = getResults(plays, { year: 1611 }) console.log(testOne) console.log(testTwo)

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