javascript - 如何比较两个对象数组并获取共同对象

标签 javascript arrays node.js lodash ramda.js

大家好,我有两个数组

var elements = [{
        "id": "id_1",
        "type": "input",
        "businesstype": { "type": "text" }
    },
    {
        "type": "label",
        "id": "id_234"
    },
    {
        "id": "id_16677",
        "type": "div",
    },
    {
        "id": "id_155",
        "type": "input",
        "businesstype": { "type": "password" }
    }
]

var filterArray=[{type:'input',businesstype:{type:'text'}},{type:'div'}]

并且想要像

var output = [{
        "id": "id_1",
        "type": "input",
        "businesstype": { "type": "text" }
    },
    {
        "id": "id_16677",
        "type": "div",
    }
]
这样的通用对象

如何比较这两个对象以从元素中获取相等的对象。

最佳答案

您可以使用嵌套对象的递归方法对其进行过滤。

const isObject = o => o && typeof o === 'object',
      isEqual = (f, o) =>
          isObject(o) && Object.keys(f).every(k =>
              isObject(f[k]) && isEqual(f[k], o[k]) || o[k] === f[k]
          );

var elements = [{ id: "id_1", type: "input", businesstype: { type: "text" } }, { type: "label", id: "id_234" }, { id: "id_16677", type: "div" }, { id: "id_155", type: "input", businesstype: { type: "password" } }],
    filterArray = [{ type: 'input', businesstype: { type: 'text' } }, { type: 'div' }],
    result = elements.filter(o => filterArray.some(f => isEqual(f, o)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何比较两个对象数组并获取共同对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45454259/

相关文章:

arrays - 我可以从 View Controller 文件访问 dataArray 但出现错误 Fatal error : Index out of range?

ios - Swift 以编程方式设置文本字段的占位符

c - 动态增加 Struct "C"中的数组大小

javascript - ECMAScript/Node : is it possible to save an object instance or context to the filesystem?

javascript - 子菜单的 jquery 切换问题

javascript - 从 Angular 4 将数据发布到 Firebase

javascript - 如何避免重新解析 XFBML 元素?

python - npm - "Can' t 找到 Python 可执行文件 "python",您可以设置 PYTHON 环境变量。”

javascript - 将新对象添加到数组

javascript - 与 jsx 中的 split 相反