lodash#cloneDeep JavaScript Examples

The following examples show how to use lodash#cloneDeep. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: util.db.js    From goindex-theme-acrou with MIT License 7 votes vote down vote up
/**
 * @description 获取数据
 * @description 效果类似于取值 dbName.path || defaultValue
 * @param {Object} payload dbName {String} 数据库名称
 * @param {Object} payload path {String} 存储路径
 * @param {Object} payload defaultValue {*} 取值失败的默认值
 * @param {Object} payload user {Boolean} 是否区分用户
 */
export function dbGet ({
  dbName = 'database',
  path = '',
  defaultValue = '',
  user = false
}) {
  return new Promise(resolve => {
    resolve(cloneDeep(db.get(pathInit({
      dbName,
      path,
      user,
      defaultValue
    })).value()))
  })
}
Example #2
Source File: util.db.js    From django-vue-admin-pro with Apache License 2.0 7 votes vote down vote up
/**
 * @description 获取数据
 * @description 效果类似于取值 dbName.path || defaultValue
 * @param {Object} payload dbName {String} 数据库名称
 * @param {Object} payload path {String} 存储路径
 * @param {Object} payload defaultValue {*} 取值失败的默认值
 * @param {Object} payload user {Boolean} 是否区分用户
 */
export function dbGet ({
  dbName = 'database',
  path = '',
  defaultValue = '',
  user = false
}) {
  return cloneDeep(db.get(pathInit({
    dbName,
    path,
    user,
    defaultValue
  })).value())
}
Example #3
Source File: tree-utils.js    From mixbox with GNU General Public License v3.0 7 votes vote down vote up
/**
 * 根据key,查询其所有后代节点,一般会用于删除
 * @param {Array} rows 具有key,parentKey关系的扁平数据结构
 * @param {object} key 要查询的节点 key
 * @returns {Array}
 */
export function getGenerationsByKey(rows, key) {
    // 这个函数会被多次调用,对rows做深拷贝,否则会产生副作用。
    rows = cloneDeep(rows);
    const parentNode = rows.find(item => item.key === key);
    if (!parentNode) return [];


    let nodes = [parentNode];
    let generationNodes = [cloneDeep(parentNode)];

    // 存放要处理的节点
    let toDo = nodes.map((v) => v);

    while (toDo.length) {
        // 处理一个,头部弹出一个。
        let node = toDo.shift();
        // 获取子节点。
        rows.forEach(row => {
            if (row.parentKey === node.key) {
                let child = cloneDeep(row);
                generationNodes.push(child);
                // child加入toDo,继续处理
                toDo.push(child);
            }
        });
    }
    return generationNodes;
}
Example #4
Source File: util.db.js    From careyshop-rest with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * @description 获取数据
 * @description 效果类似于取值 dbName.path || defaultValue
 * @param {Object} payload dbName {String} 数据库名称
 * @param {Object} payload path {String} 存储路径
 * @param {Object} payload defaultValue {*} 取值失败的默认值
 */
export function dbGet({
  dbName = 'database',
  path = '',
  defaultValue = ''
}) {
  return cloneDeep(db.get(pathInit({
    dbName,
    path,
    defaultValue
  })).value())
}
Example #5
Source File: utils.js    From hzero-front with Apache License 2.0 7 votes vote down vote up
/**
 * 合并 Descriptor 后的属性
 * @param {Object} dealProps2 - 组件属性处理后的属性
 * @param {Object} contextProps - context 属性
 */
function mergeProps(dealProps2, contextProps) {
  const dealProps3 = cloneDeep(dealProps2);
  forEach(contextProps, (_, contextPropKey) => {
    Object.defineProperty(
      dealProps3,
      contextPropKey,
      Object.getOwnPropertyDescriptor(contextProps, contextPropKey)
    );
  });
  return dealProps3;
}
Example #6
Source File: util.db.js    From qatrade_admin with MIT License 7 votes vote down vote up
/**
 * @description 获取数据
 * @description 效果类似于取值 dbName.path || defaultValue
 * @param {Object} payload dbName {String} 数据库名称
 * @param {Object} payload path {String} 存储路径
 * @param {Object} payload defaultValue {*} 取值失败的默认值
 * @param {Object} payload user {Boolean} 是否区分用户
 */
export function dbGet ({
  dbName = 'database',
  path = '',
  defaultValue = '',
  user = false
}) {
  return new Promise(resolve => {
    resolve(cloneDeep(db.get(pathInit({
      dbName,
      path,
      user,
      defaultValue
    })).value()))
  })
}
Example #7
Source File: index.js    From HexactaLabs-NetCore_React-Initial with Apache License 2.0 6 votes vote down vote up
function handleNewProvider(state, { provider }) {
  return {
    ...state,
    ids: state.ids.concat([provider.id]),
    byId: {
      ...state.byId,
      [provider.id]: cloneDeep(provider)
    }
  };
}
Example #8
Source File: Mappers.js    From sampo-ui with MIT License 6 votes vote down vote up
mergeDataItems = (itemA, itemB) => {
  const merged = cloneDeep(itemA)
  const keys = Object.keys(itemB)
  for (let i = 0; i < keys.length; i++) {
    const itemBkey = keys[i]
    if (Object.prototype.hasOwnProperty.call(itemA, itemBkey)) {
      merged[itemBkey].value += itemB[itemBkey].value
    } else {
      merged[itemBkey] = itemB[itemBkey]
    }
  }
  return merged
}
Example #9
Source File: foodCooking.js    From space-station-13-idle with GNU Affero General Public License v3.0 6 votes vote down vote up
premiumFoodEntries = Object.entries(FOOD).map(entry => {
	let originalId = entry[0];
	let originalItem = entry[1];

	let newFood = cloneDeep(originalItem);
	newFood.name = "Quality " + newFood.name;
	newFood.healAmount = Math.round(newFood.healAmount * 1.3);
	newFood.sellPrice *= 2;
	newFood.nocomplete = true; // don't count quality foods towards completion percentage
	for (let statId of Object.keys(newFood.stats)) {
		if (newFood.stats[statId] > 0)
			newFood.stats[statId] = Math.round(newFood.stats[statId]);
			newFood.stats.luck = 5;
	}
	return ["q_" + originalId, newFood];
})
Example #10
Source File: admin.getters.spec.js    From common-hosted-form-service with Apache License 2.0 6 votes vote down vote up
describe('admin getters', () => {
  let store;

  const sampleState = {
    apiKey: undefined,
    form: {},
    formList: [],
    user: {},
    userList: []
  };

  beforeEach(() => {
    store = new Vuex.Store(cloneDeep(adminStore));
    store.replaceState(cloneDeep(sampleState));
  });

  it('apiKey should return the state apiKey', () => {
    expect(store.getters.apiKey).toEqual(sampleState.apiKey);
  });

  it('form should return the state form', () => {
    expect(store.getters.form).toEqual(sampleState.form);
  });

  it('formList should return the state formList', () => {
    expect(store.getters.formList).toEqual(sampleState.formList);
  });

  it('user should return the state user', () => {
    expect(store.getters.user).toEqual(sampleState.user);
  });

  it('userList should return the state userList', () => {
    expect(store.getters.userList).toEqual(sampleState.userList);
  });
});
Example #11
Source File: rollup.config.js    From web-performance-monitor with MIT License 6 votes vote down vote up
minimize = (obj) => {
  const minObj = cloneDeep(obj)
  minObj.file = minObj.file.slice(0, minObj.file.lastIndexOf('.js')) + '.min.js'
  minObj.plugins = [
    terser({
      compress: { drop_console: !isDev },
      format: {
        comments: RegExp(`${pkg.name}`)
      }
    })
  ]
  minObj.banner = banner
  return minObj
}
Example #12
Source File: helpers.js    From gatsby-source-wordpress-experimental with MIT License 6 votes vote down vote up
getTypeSettingsByType = (type) => {
  if (!type) {
    return {}
  }

  const typeName = findTypeName(type)

  const cachedTypeSettings = typeSettingCache[typeName]

  if (cachedTypeSettings) {
    return cachedTypeSettings
  }

  // the plugin options object containing every type setting
  const allTypeSettings = store.getState().gatsbyApi.pluginOptions.type

  const typeSettings = cloneDeep(allTypeSettings[typeName] || {})

  // the type.__all plugin option which is applied to every type setting
  const __allTypeSetting = cloneDeep(allTypeSettings.__all || {})

  if (typeName === `MediaItem`) {
    delete __allTypeSetting.limit
    delete typeSettings.limit
  }

  if (typeSettings) {
    const mergedSettings = merge(__allTypeSetting, typeSettings)

    typeSettingCache[typeName] = mergedSettings

    return mergedSettings
  }

  typeSettingCache[typeName] = __allTypeSetting

  return __allTypeSetting
}
Example #13
Source File: index.js    From mixbox with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 从数组中删除一个元素
 * @param {Array} arr 需要操作的数组
 * @param {*} item 要删除的元素,注意:内部是用'==='比对的
 */
export function arrayRemove(arr, item) {
    if (!arr || !Array.isArray(arr) || !arr.length) return arr;
    const newArr = cloneDeep(arr);
    let itemIndex = -1;
    for (let i = 0; i < newArr.length; i++) {
        if (newArr[i] === item) {
            itemIndex = i;
            break;
        }
    }
    if (itemIndex > -1) {
        newArr.splice(itemIndex, 1);
    }
    return newArr;
}
Example #14
Source File: db.js    From d2admin-permission with MIT License 6 votes vote down vote up
/**
 * @description 获取数据
 * @description 效果类似于取值 dbName.path || defaultValue
 * @param {Object} payload dbName {String} 数据库名称
 * @param {Object} payload path {String} 存储路径
 * @param {Object} payload defaultValue {*} 取值失败的默认值
 * @param {Object} payload user {Boolean} 是否区分用户
 */
export function dbGet ({
  dbName = 'database',
  path = '',
  defaultValue = '',
  user = false
}) {
  return cloneDeep(db.get(pathInit({
    dbName,
    path,
    user,
    defaultValue
  })).value())
}
Example #15
Source File: app-settings.js    From loa-details with GNU General Public License v3.0 6 votes vote down vote up
export function getSettings() {
  let appSettings = cloneDeep(defaultSettings);

  try {
    let settingsStr = store.get("settings");

    if (typeof settingsStr === "object")
      appSettings = merge(appSettings, cloneDeep(settingsStr));
    else if (typeof settingsStr === "string")
      merge(appSettings, JSON.parse(settingsStr));

    log.info("Found and applied settings.");
  } catch (e) {
    log.info("Setting retrieval failed: " + e);
  }

  return appSettings;
}
Example #16
Source File: DataModel.js    From see-h5-editor with Apache License 2.0 6 votes vote down vote up
getElementConfig = function (element, extendStyle = {}) {
    let elementData = cloneDeep(element)
    let type = elementData.valueType || 'String' // 默认string类型
    let dict = {
        'Sting': '',
        'Array': [],
        'Object': {},
        'Boolean': false,
        'Number': 0
        // 待扩展数据类型
    }
    const uuid = createUUID()
    let elementConfigData = cloneDeep(elementConfig)
    let config = {
        ...elementConfigData,
        uuid: uuid,
        brotherUuid: uuid,
        elName: elementData.elName,
        propsValue: cloneDeep(elementData.needProps || {})
    }

    // 样式
    config.commonStyle = merge(config.commonStyle, elementData.defaultStyle)
    config.commonStyle = merge(config.commonStyle, extendStyle)

    config.resizable = elementData.resizable
    config.movable = elementData.movable
    config.autoHeight = elementData.autoHeight || false
    config.autoWidth = elementData.autoWidth || false

    config.value = element.defaultValue || dict[type]
    config.valueType = type
    config.isForm = !!element.isForm
    config.componentsType = element.componentsType
    config.visible = typeof element.visible === 'string' ? element.visible : 'return true'
    config.hasSlot = !!element.hasSlot

    return config
}
Example #17
Source File: index.js    From HexactaLabs-NetCore_React-Final with Apache License 2.0 6 votes vote down vote up
function handleNewProduct(state, { product }) {
  return {
    ...state,
    ids: state.ids.concat([product.id]),
    byId: {
      ...state.byId,
      [product.id]: cloneDeep(product)
    }
  };
}
Example #18
Source File: index.js    From HexactaLabs-NetCore_React-Level1 with Apache License 2.0 6 votes vote down vote up
function handleNewProductType(state, { producttype }) {
  return {
    ...state,
    ids: state.ids.concat([producttype.id]),
    byId: {
      ...state.byId,
      [producttype.id]: cloneDeep(producttype),
    },
  };
}
Example #19
Source File: localeApi.js    From hzero-front with Apache License 2.0 6 votes vote down vote up
/**
 * 获取 ui 库 的多语言, 如果传了 language 和 promptKey, 那么使用传递的 多语言来覆盖 ui库多语言
 * @param {function()} loadFileIntl - 获取文件多语言的方法: () => Promise<any>
 * @param {string} language - 语言
 * @param {string} promptKey - 多语言编码前缀
 * @return {Promise<*>}
 */
export async function getFileIntl(loadFileIntl = () => {}, language, promptKey) {
  const organizationId = getCurrentOrganizationId();
  let l = {};
  try {
    // 加载文件
    l = await loadFileIntl();
    l = cloneDeep(resolveRequire(l));
  } catch (e) {
    l = {};
  }
  let iRes = {};
  if (language && promptKey && organizationId !== undefined) {
    // 加载 多语言
    iRes = await queryPromptLocale(organizationId, language, promptKey);
    const i = getResponse(iRes) || {};
    const prefixLen = promptKey.length + 1;
    // 覆盖 ui库 多语言
    Object.keys(i).forEach(intlCode => {
      set(l, intlCode.substr(prefixLen), i[intlCode]);
    });
  }
  return l;
}
Example #20
Source File: index.js    From HexactaLabs-NetCore_React-Level1 with Apache License 2.0 6 votes vote down vote up
function handleNewProductType(state, { producttype }) {
  return {
    ...state,
    ids: state.ids.concat([producttype.id]),
    byId: {
      ...state.byId,
      [producttype.id]: cloneDeep(producttype)
    }
  };
}
Example #21
Source File: data.js    From dynamic-form-render with MIT License 6 votes vote down vote up
formatByProps = (data, props, propsMap = {}) => {
  if (
    !isObjectLike(data) ||
    !props ||
    !isPlainObject(props) ||
    !isPlainObject(propsMap)
  ) {
    return data
  }

  const map = Object.assign({}, props, propsMap)
  if (isArray(data)) {
    return data.map(item => {
      if (!isPlainObject(item)) {
        return item
      }
      let replaceObj = cloneDeep(item)
      for (const key in map) {
        if (map.hasOwnProperty(key) && key !== map[key]) {
          replaceObj[key] = item[map[key]]
        }
      }
      return replaceObj
    })
  }
  const result = cloneDeep(data)
  for (const key in map) {
    if (map.hasOwnProperty(key) && key !== map[key]) {
      result[key] = data[map[key]]
    }
  }
  return result
}
Example #22
Source File: constants.js    From html-to-docx with MIT License 6 votes vote down vote up
defaultDocumentOptions = {
  orientation: defaultOrientation,
  margins: cloneDeep(portraitMargins),
  title: '',
  subject: '',
  creator: applicationName,
  keywords: [applicationName],
  description: '',
  lastModifiedBy: applicationName,
  revision: 1,
  createdAt: new Date(),
  modifiedAt: new Date(),
  headerType: 'default',
  header: false,
  footerType: 'default',
  footer: false,
  font: defaultFont,
  fontSize: defaultFontSize,
  complexScriptFontSize: defaultFontSize,
  table: {
    row: {
      cantSplit: false,
    },
  },
  pageNumber: false,
  skipFirstHeaderFooter: false,
  lineNumber: false,
  lineNumberOptions: {
    countBy: 1,
    start: 0,
    restart: 'continuous',
  },
}
Example #23
Source File: definition.js    From jafar with MIT License 6 votes vote down vote up
function createResources(initialResources) {
  // we cant allow users to change the form internal fields outside jafar, since it will not trigger the form's lifecycle and
  // also can harm the form validity and cause runtime unexpected errors (for example - by removing one of the model.validators)
  const resources = cloneDeep(initialResources);

  let result = {
    components: resources.components || {},
    dependenciesChanges: resources.dependenciesChanges || {},
    validators: merge(cloneDeep(validators), resources.validators || {}),
    conversions: merge(cloneDeep(conversions), resources.conversions || {}),
    terms: merge(cloneDeep(terms), resources.terms || {}),
    hooks: merge(cloneDeep(hooks), resources.hooks || {}),
  };

  // apply custom object fields to the result
  result = Object.assign(resources, result);
  return result;
}
Example #24
Source File: index.js    From HexactaLabs-NetCore_React-Initial with Apache License 2.0 5 votes vote down vote up
function handleUpdateProvider(state, { provider }) {
  return {
    ...state,
    byId: { ...state.byId, [provider.id]: cloneDeep(provider) }
  };
}
Example #25
Source File: bartending.js    From space-station-13-idle with GNU Affero General Public License v3.0 5 votes vote down vote up
BARTENDING = merge(cloneDeep(jobBase), cloneDeep(jobSingleAction), {
	getters: {
		jobId() {
			return "bartending";
		},
		drinkTableCount(state, getters, rootState, rootGetters) {
			let count = 0;
			let bankItemIds = rootGetters["inventory/bankItemIds"];
			bankItemIds.forEach(bankItemId => {
				if (ITEMS[bankItemId].isDrink) count += 1;
			});
			return count;
		},
		drinkTableMax(state, getters, rootState, rootGetters) {
			let upgradeCount = rootGetters["upgrades/get"]("drinkTable");
			return upgradeCount * BARTENDING_UPGRADE_CAP;
		},
		drinkTableBonus(state, getters) {
			return Math.min(getters["drinkTableCount"], getters["drinkTableMax"]) * BARTENDING_UPGRADE_INCREMENT;
		},
		baseActions(state, getters, rootState, rootGetters) {
			let actions = cloneDeep(ACTIONS);

			let potion = rootGetters["potions/get"]("bartending");
			let potionItemId = potion ? potion.itemId : null;

			for (let action of Object.values(actions)) {
				action.time *= 1 / (1 + getters["drinkTableBonus"]);

				if (potionItemId == "potionBartending") {
					if (getters["level"] < action.requiredLevel) {
						action.requiredLevel -= 10;
						action.levelReduced = true;
					} else {
						action.preservePotion = true;
					}
				} else if (potionItemId == "toolBartending") {
					let originalItems = action.items;
					delete action.items;
					action.itemTables = [
						{
							chance: 1,
							items: originalItems
						},
						{
							chance: 1,
							items: {
								id: "money",
								count: ITEMS[originalItems.id].sellPrice * 2
							}
						}
					]
				}
			}

			return actions;
		},
		locked(state, getters, rootState, rootGetters) {
			return !rootGetters["upgrades/get"]("bartendingUnlocked");
		},
	},
})
Example #26
Source File: store.js    From holo-schedule with MIT License 5 votes vote down vote up
createStore = () => {
  const data = {}
  const dataToSync = {}

  const callbacks = []
  console.log('[background/store]listening to store')
  const port = listen('store', {
    onConnect: $port => Object.entries(data).forEach(([key, value]) => {
      $port.postMessage({ key, value })
    }),
  })

  const uploadToSync = async () => {
    if (data[SHOULD_SYNC_SETTINGS]) {
      await storage.sync.set({ store: dataToSync })
    }
  }

  const set = async (obj, { local = true, sync = false } = { local: true, sync: false }) => {
    Object.entries(obj).forEach(([key, value]) => {
      console.log(`[background/store]${key} has been stored/updated successfully.`)

      const oldValue = data[key]
      data[key] = value

      callbacks.forEach(callback => callback(key, value, oldValue))

      port.postMessage({ key, value })
    })
    if (local) {
      await withLock(async () => storage.local.set({ store: { ...await getStorage('local'), ...obj } }))
    }
    if (sync) {
      Object.assign(dataToSync, obj)

      await uploadToSync()
    }
  }

  const downloadFromSync = async () => {
    Object.assign(dataToSync, await getStorage('sync'))
    if (data[SHOULD_SYNC_SETTINGS]) {
      await set(dataToSync, { local: false })
    }
  }

  return {
    data,
    dataToSync,
    callbacks,
    downloadFromSync,
    uploadToSync,
    set,
    async init() {
      await set(await getStorage('local'), { local: false })

      await downloadFromSync()

      this.subscribe(SHOULD_SYNC_SETTINGS, async () => {
        await uploadToSync()
      })
    },
    get(key) {
      return cloneDeep(data[key])
    },
    subscribe(key = '', callback = noop) {
      callbacks.push(($key, ...args) => {
        if (key === $key) {
          callback(...args)
        }
      })
    },
  }
}
Example #27
Source File: admin.mutations.spec.js    From common-hosted-form-service with Apache License 2.0 5 votes vote down vote up
describe('admin mutations', () => {
  let state;

  beforeEach(() => {
    state = cloneDeep(store.state);
  });

  it('SET_API_KEY should update apiKey state', () => {
    const obj = { foo: 'bar' };
    store.mutations.SET_API_KEY(state, obj);

    expect(state.apiKey).toBeTruthy();
    expect(state.apiKey).toEqual(expect.objectContaining(obj));
  });

  it('SET_FORM should update form state', () => {
    const obj = { foo: 'bar' };
    store.mutations.SET_FORM(state, obj);

    expect(state.form).toBeTruthy();
    expect(state.form).toEqual(expect.objectContaining(obj));
  });

  it('SET_FORMLIST should update formList state', () => {
    const obj = { foo: 'bar' };
    store.mutations.SET_FORMLIST(state, [obj]);

    expect(state.formList).toBeTruthy();
    expect(state.formList).toHaveLength(1);
    expect(state.formList).toEqual(expect.arrayContaining([expect.objectContaining(obj)]));
  });

  it('SET_USER should update form state', () => {
    const obj = { foo: 'bar' };
    store.mutations.SET_USER(state, obj);

    expect(state.user).toBeTruthy();
    expect(state.user).toEqual(expect.objectContaining(obj));
  });

  it('SET_USERLIST should update formList state', () => {
    const obj = { foo: 'bar' };
    store.mutations.SET_USERLIST(state, [obj]);

    expect(state.userList).toBeTruthy();
    expect(state.userList).toHaveLength(1);
    expect(state.userList).toEqual(expect.arrayContaining([expect.objectContaining(obj)]));
  });
});
Example #28
Source File: enrollmentReducer.js    From datapass with GNU Affero General Public License v3.0 5 votes vote down vote up
eventUpdateFactory =
  (demarches = null) =>
  ({
    previousEnrollment,
    event: {
      target: { type = null, checked = null, value: inputValue, name },
    },
  }) => {
    const value = type === 'checkbox' ? checked : inputValue;

    let futureEnrollment = cloneDeep(previousEnrollment);
    set(futureEnrollment, name, value);

    if (demarches && name === 'demarche') {
      const defaultDemarche = get(demarches, 'default', {});
      const selectedDemarche = get(demarches, value, {});

      let futureTeamMembers = futureEnrollment.team_members;
      if (
        !isEmpty(futureEnrollment.team_members) &&
        !isEmpty(defaultDemarche.team_members)
      ) {
        futureTeamMembers = futureEnrollment.team_members.map(
          (futureTeamMember) => {
            if (!defaultDemarche.team_members[futureTeamMember.type]) {
              return futureTeamMember;
            }

            if (
              !selectedDemarche.team_members ||
              !selectedDemarche.team_members[futureTeamMember.type]
            ) {
              return defaultDemarche.team_members[futureTeamMember.type];
            }

            return selectedDemarche.team_members[futureTeamMember.type];
          }
        );
      }

      futureEnrollment = merge(
        {},
        futureEnrollment,
        defaultDemarche.state,
        selectedDemarche.state,
        { team_members: futureTeamMembers }
      );
    }

    return futureEnrollment;
  }
Example #29
Source File: env.js    From d2admin-permission with MIT License 5 votes vote down vote up
env = cloneDeep(process.env)