根据该对象中

时间:2017-10-15 22:40:08

标签: javascript arrays 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。谢谢!

2 个答案:

答案 0 :(得分:2)

我使用过滤器然后映射,即

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 */ [])

答案 1 :(得分: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 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]