簡體   English   中英

獲取數組中包含字符串中最匹配ID屬性的對象?

[英]Get object in array that contains closest matching id property in a string?

我想知道是否有更好的方法來獲得結果。 我有一個對象數組,每個對象都包含一個ID作為字符串路徑模式。 我想將最匹配的對象返回到URL路徑。 我正在使用Lodash的ATM

所有ID都是唯一的。

 const url = '/economia/finanzas/moodys-coloca-calificaciones-de-riesgo-de-costa/JZF24QAQHBBFPLJQL5VZJPKCZA/story/' const sites = [{ '_id': '/la-nacion/economia' }, { '_id': '/la-nacion' }, { '_id': '/la-nacion/economia/finanzas' }, { '_id': '/la-nacion/economia/moodys' }] const urlArr = url.split('/') const compare = sites.map(site => { // get all matches const siteArr = site._id.split('/') // get lengths of matches return _.intersection(siteArr, urlArr).length }) // get index of obj with best match const indexOfBestMatch = _.indexOf(compare, _.max(compare)) // new primary section const newPrimarySection = sites.filter((e, i) => { return i === indexOfBestMatch }) console.log(newPrimarySection) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script> 

https://jsbin.com/lumepereyi/1/edit?js,console

不需要庫,您可以使用reduce來遍歷_id的數組,並保留_id字符串匹配數的計數,以便將其解析為匹配次數最多的一個:

 const url = '/economia/finanzas/moodys-coloca-calificaciones-de-riesgo-de-costa/JZF24QAQHBBFPLJQL5VZJPKCZA/story/'; const sites = [{ '_id': '/la-nacion/economia' }, { '_id': '/la-nacion' }, { '_id': '/la-nacion/economia/finanzas' }, { '_id': '/la-nacion/economia/moodys' }]; const substrings = new Set(url.split('/')); const countMatches = str => str.split('/').reduce((a, substr) => a + (substrings.has(substr)), 0); const { bestMatch } = sites.reduce(({ bestMatch, count=0 }, { _id }) => { const thisCount = countMatches(_id); return thisCount > count ? { count: thisCount, bestMatch: _id } : { count, bestMatch }; }, {}); console.log(bestMatch); 

由於只需要具有最大匹配項的項目,因此可以使用_.maxBy()迭代網站數組並提取項目。 使用_.get()提取_id的值,因為如果sites為空,則_.get()不會引發錯誤:

 const url = '/economia/finanzas/moodys-coloca-calificaciones-de-riesgo-de-costa/JZF24QAQHBBFPLJQL5VZJPKCZA/story/' const sites = [{"_id":"/la-nacion/economia"},{"_id":"/la-nacion"},{"_id":"/la-nacion/economia/finanzas"},{"_id":"/la-nacion/economia/moodys"}] const getPrimarySection = (url, sites) => { const urlArr = url.split('/') return _.get(_.maxBy(sites, site => { const siteArr = site._id.split('/') return _.intersection(siteArr, urlArr).length }), '_id') } const newPrimarySection = getPrimarySection(url, sites) console.log(newPrimarySection) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script> 

如果您的path前綴始終相同(例如/la-naction似乎相同),則可以根據匹配字符串的長度(通過startsWith )進行自己的評分,然后sort-by desc (最大分數)進行sort-by desc 。並獲得最高分:

 const url = '/economia/finanzas/moodys-coloca-calificaciones-de-riesgo-de-costa/JZF24QAQHBBFPLJQL5VZJPKCZA/story/' const sites = [{"_id":"/la-nacion/economia"},{"_id":"/la-nacion"},{"_id":"/la-nacion/economia/finanzas"},{"_id":"/la-nacion/economia/moodys"}] const getBestMatch = (s, u, p = '/la-nacion') => { // <-- default prefix const topScored = s.map(x => (Object.assign(x, { score: ((`${p}${u}`).startsWith(x._id) ? x._id.length : 0)}), x) ).sort((a, b) => b.score - a.score)[0] // <-- sort, get the highest score return topScored.score > 0 ? topScored._id : undefined } console.log(getBestMatch(sites, url)) 

無需擔心,它只是添加分數然后真正sort map

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM