How to compare two array of object and get common objects

后端 未结 3 409
太阳男子
太阳男子 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:52

    (Since you tagged Ramda)

    Ramda already has many useful (object) comparison functions you can use to make the filter a bit easier to read. (i.e.: equals and other functions that use it under the hood, like contains)

    You could, for example, write:

    const 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"}}];
    const filterArray=[{type:'input',businesstype:{type:'text'}},{type:'div'}];
    
    // Describes how to define "equality"
    // i.e.: elements are equal if type and businesstype match
    // e.g.: pick(["a", "b"], { a: 1, b: 2, c: 3}) -> { a: 1, b: 2}
    const comparisonObjectFor = pick(["type", "businesstype"]);
    
    // Compares an object's comparison representation to another object
    const elEquals = compose(whereEq, comparisonObjectFor);
    
    // Creates a filter method that searches an array
    const inFilterArray = matchElements => el => any(elEquals(el), matchElements);
    
    // Run the code on our data
    filter(inFilterArray(filterArray), elements);
    

    Running example here

    I don't think this is necessarily the best solution (in terms of reusability, readability), but I'd advice you to not inline deep object/array comparison methods since:

    1. You're probably going to use them more than once
    2. They are hard to understand/predict if not given the right name & documentation
    3. They are prone to (small) bugs because of their complexity

    In other words: since you've tagged lodash and Ramda, I can safely advice to use a well tested, well used library for the comparison of your objects.

提交回复
热议问题