搜索数组作为对象的属性并返回相应的键

时间:2018-11-27 23:53:28

标签: javascript ecmascript-6 frontend

大家好,我正在尝试找到一种更干净,更可靠的方法来完成此任务。

说我有一个对象调用total

const total = { 
                toDevice: [{'a':'a'},{'b':'b'},], 
                fromDevice: [{'c':'c'},{'c':'c'},]
               };

并假设我像这样将toDevicefromDevice的两个数组都进行了短克隆

const copiedArr = [...total.toDevice, ...total.fromDevice]

我在此copiedArr数组中获得了一个对象的引用。

const a = copiedArr[1];

然后我要进行搜索以返回total对象内部用于引用的对应键。

例如,如果我搜索a,它将返回字符串toDevice

这是我想出的解决方案

Object.keys(total).filter(key => {
  return total[key].indexOf(a) !== -1;
})[0]

不要以为这是最好的方法。你们有更好的解决方案吗?

1 个答案:

答案 0 :(得分:2)

由于您最初的问题不清楚我是否要匹配子数组对象中的键或值,因此我为每种用例编写了一个示例:

const total = { 
  toDevice: [{ a: 1 }, { b: 2 }], 
  fromDevice: [{ c: 3 }, { d: 4 }]
}

const matchKey = (needle, haystack) => (
  Object.entries(total).find(
    ([key, value]) => value.some(item => Object.keys(item).includes(needle))
  ) || []
)[0]

console.log(matchKey('a', total))

const matchValue = (needle, haystack) => (
  Object.entries(total).find(
    ([key, value]) => value.some(item => Object.values(item).includes(needle))
  ) || []
)[0]

console.log(matchValue(4, total))

鉴于您随后对该问题进行的编辑和说明,我建议采用以下方式:

const total = { 
  toDevice: [{'a':'a'},{'b':'b'}], 
  fromDevice: [{'c':'c'},{'c':'c'}]
}

const a = [...total.toDevice, ...total.fromDevice][1]

const matchObject = (needle, haystack) => (
  Object.entries(haystack).find(
    ([key, value]) => value.includes(needle)
  ) || []
)[0]

console.log(matchObject(a, total))

注释:

    在此用例中,
  1. Object.entriesObject.keys更符合人体工程学。
  2. Array.prototype.find会在找到匹配项后立即在数组上进行迭代(而不是Array.prototype.filter,后者将始终在整个数组上进行迭代)。
  3. Array.prototype.includes几乎总是比Array.prototype.indexOf更符合人体工程学。

文档:

Object.prototype.entries

Array.prototype.find

Array.prototype.some

Array.prototype.includes