在单独的对象中查找匹配值

时间:2018-05-09 00:16:00

标签: javascript arrays javascript-objects

我有两个对象:

const have = {
  a: true,
  b: {
    c: true,
    d: true
  }
};

const need = {
  a: false,
  b: {
    c: true,
    d: false
  }
};

我需要找到" need" obj,如果至少有一个正匹配(true)与"有" OBJ。在这种情况下,它们在b.c中匹配,因为两者都是真的。

我应该如何面对这个想法?也许先解析一个数组?循环obj?

更新

需要' obj,并不总是包含所有相同的键。它可能有更少,但没有不同。

示例:

const need = {
  b: {
    c: true,
  }
};

2 个答案:

答案 0 :(得分:1)

如果键和对象结构总是匹配,则可以对键/值进行递归检查:



const have = {
  a: true,
  b: {
    c: true,
    d: true
  }
};

const need = {
  a: false,
  b: {
    c: true,
    d: false
  }
};

function objectsHaveMatch(obj1, obj2) {
  return Object.entries(obj1).some(([key, obj1Val]) => {
    if (!obj2[key]) return false;
    if (typeof obj1Val !== 'boolean') return objectsHaveMatch(obj1Val, obj2[key]);
    return obj1Val === true && obj2[key] === true;
	});
}

const atLeastOneMatch = objectsHaveMatch(have, need);
console.log(atLeastOneMatch);




也适用于更复杂的结构:



const have = {
  a: true,
  b: {
    c: false,
    d: true,
    foo: {
      q: false,
      w: false,
      e: false,
      r: {
        t: true
      }
    }
  }
};

const need = {
  a: false,
  b: {
    c: true,
    d: false,
    foo: {
      q: true,
      w: true,
      e: true,
      r: {
        t: false
      }
    }
  }
};

function objectsHaveMatch(obj1, obj2) {
  return Object.entries(obj1).some(([key, obj1Val]) => {
    if (!obj2[key]) return false;
    if (typeof obj1Val !== 'boolean') return objectsHaveMatch(obj1Val, obj2[key]);
    return obj1Val === true && obj2[key] === true;
	});
}

const atLeastOneMatch = objectsHaveMatch(have, need);
console.log(atLeastOneMatch);




包含缺少属性的代码段示例:



const have = {
  a: true,
  b: {
    c: true,
    d: true,
    foo: {
      q: false,
      w: false,
      e: false,
      r: {
        t: true
      }
    }
  }
};

const need = {
  b: {
    c: true,
  }
};

function objectsHaveMatch(obj1, obj2) {
  return Object.entries(obj1).some(([key, obj1Val]) => {
    if (!obj2[key]) return false;
    if (typeof obj1Val !== 'boolean') return objectsHaveMatch(obj1Val, obj2[key]);
    return obj1Val === true && obj2[key] === true;
	});
}

const atLeastOneMatch = objectsHaveMatch(have, need);
console.log(atLeastOneMatch);




答案 1 :(得分:0)

与接受的答案类似的方法,除了下面针对OP的特定用例稍微优化一点,假设数据是“模仿的”,并且比较值是对象或'真实'。

const have = { a: true, b: { c: true, d: true } };
const need = { b: { c: true } };

const hn = (h, n) => // 'have/need' iterator
  Object.keys(n).some(i => // at least one truthy 'need':
    typeof n[i] === 'object' && hn(h[i], n[i]) // recursive on object
    || n[i] && n[i] === h[i]); // or both h & n are equal and truthy


const has = hn(have, need);
console.log(has);

相关问题