编程语言
首页 > 编程语言> > javascript – 如何比较两个对象数组并获取常见对象

javascript – 如何比较两个对象数组并获取常见对象

作者:互联网

大家好我有两个阵列

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; }

标签:ramda-js,javascript,arrays,node-js,lodash
来源: https://codeday.me/bug/20191003/1849881.html