How to compare two array of object and get common objects

后端 未结 3 413
太阳男子
太阳男子 2020-12-22 11:12

Hello guys I have two arrays

var elements = [{
        \"id\": \"id_1\",
        \"type\": \"input\",
        \"businesstype\": { \"type\": \"text\" }
    },         


        
3条回答
  •  生来不讨喜
    2020-12-22 11:28

    You could filter it with a recursive approach for the nested objects.

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

提交回复
热议问题