簡體   English   中英

根據該對象中其他兩個屬性的值獲取Javascript對象屬性的值

[英]Get value of Javascript object property based on the values of two other properties in that object

給定下面的對象數組,如果前兩個id與傳遞給方法的內容相匹配,那么得到'thirdId數組的更好方法是什么?

 const arrObjs = [ { firstId: '1', secondId: '1', thirdId: '5' }, { firstId: '2', secondId: '1', thirdId: '12' }, { firstId: '1', secondId: '2', thirdId: '13' }, { firstId: '1', secondId: '1', thirdId: '42' }, { firstId: '1', secondId: '2', thirdId: '51' } ]; const getThirdIds = (arrObjs, firstId, secondId ) => { const thirdIds = [] arrObjs.map(obj => { if (obj.firstId == firstId && obj.secondId == secondId) { thirdIds.push(obj.thirdId) } }) return thirdIds } console.log(getThirdIds(arrObjs, 1, 1)); 

我想遠離loDash。 謝謝!

我會使用過濾器然后映射,即

return arrObjs
  .filter(obj => obj.firstId == firstId && obj.secondId == secondId)
  .map(obj => obj.thirdId)

Array.prototype.filter()將創建一個只包含匹配條目的新數組。

然后, Array.prototype.map()將該數組轉換為僅包含每個條目的thirdId屬性的數組。


如果您不熱衷於執行兩組迭代(過濾器和映射),則可以使用Array.prototype.reduce()操作

return arrObjs.reduce((/* collector */ thirdIds, /* each */ obj) => {
  if (obj.firstId == firstId && obj.secondId == secondId) {
    thirdIds.push(obj.thirdId)
  }
  return thirdIds
}, /* initial collector value */ [])

如果“更好”意味着更短:

 const arrObjs = [ { firstId: '1', secondId: '1', thirdId: '5' }, { firstId: '2', secondId: '1', thirdId: '12' }, { firstId: '1', secondId: '2', thirdId: '13' }, { firstId: '1', secondId: '1', thirdId: '42' }, { firstId: '1', secondId: '2', thirdId: '51' } ] const getThirdIds = (a, b, c) => a.reduce((r, o) => o.firstId == b && o.secondId == c ? r.concat(o.thirdId) : r, []) console.log(getThirdIds(arrObjs, 1, 1)) 


如果“更好”意味着更高效,則可以為常量O(1)搜索創建查找對象:

 const arrObjs = [ { firstId: '1', secondId: '1', thirdId: '5' }, { firstId: '2', secondId: '1', thirdId: '12' }, { firstId: '1', secondId: '2', thirdId: '13' }, { firstId: '1', secondId: '1', thirdId: '42' }, { firstId: '1', secondId: '2', thirdId: '51' } ]; const lookup = [] for (let i = 0; i < arrObjs.length; i++) { const obj = arrObjs[i], lookup1 = lookup [obj.firstId ] || (lookup [obj.firstId ] = []), lookup2 = lookup1[obj.secondId] || (lookup1[obj.secondId] = []) lookup2[lookup2.length] = +obj.thirdId } console.log(JSON.stringify(lookup)) // lookup = [,[,[5,42],[13,51]],[,[12]]] console.log(JSON.stringify(lookup[1][1])) // [5,42] 

暫無
暫無

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

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