How to transfer props of an object from one location to another?

前端 未结 4 1207
长情又很酷
长情又很酷 2020-12-20 09:39

Following is an object with some deep properties.

const InitialObj = {
    Store: {propsFromStore: {}},
    Market: {propsFromMarket: {}},
    GoDown: {prop         


        
4条回答
  •  不思量自难忘°
    2020-12-20 10:09

    You can use a first function which will find which props should serve as references (Store, Market, GoDown), and use recursion on the others, with an auxiliary function:

    const InitialObj = {
      Store: {propsFromStore: {}},
      Market: {propsFromMarket: {}},
      GoDown: {propsFromDown: {}},
      fruits: {store_c: "Store", otherProp1: {store_e: "Store", otherSubProp1: {}}, otherProp2: {}},
      vegetables: {market_d: "Market", otherProp1: {otherSubProp1: {godown_r: "GoDown", }}},
      fancy:{store_t: "Store", market_d: "Market", otherProp1: {otherSubProp1: {godown_r: "GoDown", }}},
    };
    
    function hydrateObj(obj, keys) {
      const refs = keys.reduce((o, k) => ({...o, [k]: obj[k]}), {});
      return Object.entries(obj).reduce((res, [k, v]) => {
        if(!keys.includes(k)) {
          res[k] = hydrateObjAux(v, keys, refs);
        }
        return res;
      }, {});
    }
    
    function hydrateObjAux(obj, keys, refs) {
      return Object.entries(obj).reduce((res, [k, v]) => {
        if(keys.includes(v)) {
          res[k] = refs[v];
        } else {
          res[k] = hydrateObjAux(v, keys, refs);
        }
        return res;
      }, {});
    }
    
    const res = hydrateObj(InitialObj, ['Store', 'Market', 'GoDown']);
    document.body.innerHTML = '
    ' + JSON.stringify(res, 0, 4) + '
    ';

提交回复
热议问题