简体   繁体   中英

Intersection of an array with a deeply nested object in javascript

I want to include all the keys of an object present in an array and discard the rest, For eg, if I have an array ,

const arr = ['apple', 'milk', 'bread', 'coke'];

and an object ,

const dummy = {
    apple: {
        category: 'fruit'
    },
    banana: {
        category: 'fruit'
    },
    potato: {
        category: 'vegetable'
    },
    dairy: {
        milk: {
          type: 'A2'
        }
    },
    bakery: {
        bread: {
            type: 'brown'
        }
    },
    beverage: {
      cold_drink: {
        coke: {
          type: 'diet'
        },
        beer: {
        }
      }
    }
}

I want my resultant object to contain the keys from arr only, be it direct keys or deeply nested. So for above case, my resultant object will look like,

{
    apple: {
        category: 'fruit'
    },
    dairy: {
        milk: {
          type: 'A2'
        }
    },
    bakery: {
        bread: {
            type: 'brown'
        }
    },
    beverage: {
      cold_drink: {
        coke: {
          type: 'diet'
        },
        beer: {}
      }
    }
}

I am trying to solve this via recursion , but not able to get the output correctly. Below is my code, could you please help me with where I am going wrong?

function fetchResultantObject(object, key, result) {
  if(typeof object !== 'object')
    return null;
  for(let objKey in object) {
    if(key.indexOf(objKey) > -1) {
      result[objKey] = object[objKey];
    } else {
      result[objKey] = fetchValueByKey(object[objKey], key, result);
    }
  }
  return result;
}

console.log(fetchResultantObject(dummy, arr, {}));

You could filter the entries and check if the (nested) objects contains a wanted key.

 const hasKey = object => object && typeof object === 'object' && (keys.some(k => k in object) || Object.values(object).some(hasKey)), keys = ['apple', 'milk', 'bread', 'coke'], data = { apple: { category: 'fruit' }, banana: { category: 'fruit' }, potato: { category: 'vegetable' }, dairy: { milk: { type: 'A2' } }, bakery: { bread: { type: 'brown' } }, beverage: { cold_drink: { coke: { type: 'diet' } } } }, result = Object.fromEntries(Object .entries(data) .filter(([k, v]) => hasKey({ [k]: v })) ); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM