lodash#merge JavaScript Examples

The following examples show how to use lodash#merge. 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: lang-util.js    From surveillance-forms with MIT License 7 votes vote down vote up
getLanguagesByCode = (code) => {
  if (code === DEFAULT_LANGUAGE_CODE) {
    return DEFAULT_LANGUAGE_PACK;
  }
  const merged = {};
  const languagePack = supportedLanguages[code].pack || DEFAULT_LANGUAGE_PACK;
  merge(merged, DEFAULT_LANGUAGE_PACK, languagePack);

  return merged;
}
Example #2
Source File: schema.js    From rate-repository-api with MIT License 6 votes vote down vote up
resolvers = merge(
  DateTime.resolvers,
  Repository.resolvers,
  repositoryQuery.resolvers,
  User.resolvers,
  createUserMutation.resolvers,
  authenticateMutation.resolvers,
  usersQuery.resolvers,
  meQuery.resolvers,
  repositoriesQuery.resolvers,
  PageInfo.resolvers,
  RepositoryConnection.resolvers,
  OrderDirection.resolvers,
  createReviewMutation.resolvers,
  Review.resolvers,
  ReviewConnection.resolvers,
  UserConnection.resolvers,
  deleteReviewMutation.resolvers,
)
Example #3
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 #4
Source File: traitor.js    From space-station-13-idle with GNU Affero General Public License v3.0 6 votes vote down vote up
traitor = merge(cloneDeep(jobBase), cloneDeep(jobSingleAction), {
	getters: {
		jobId() {
			return "traitor";
		},
		baseActions(state, getters, rootState, rootGetters) {
			let actions = cloneDeep(ACTIONS);

			let upgradeCount = rootGetters["upgrades/get"]("antagUpgrade");
			let potion = rootGetters["potions/get"]("traitor");
			let potionItemId = potion ? potion.itemId : null;

			for (let action of Object.values(actions)) {
				// Apply upgrades
				action.time *= 1 / (1 + ANTAG_UPGRADE_PERCENT * upgradeCount);
			}
			return actions;
		},
		locked(state, getters, rootState, rootGetters) {
			return !rootGetters["upgrades/get"]("traitorUnlocked");
		}
	}
})
Example #5
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 #6
Source File: shitposting.js    From space-station-13-idle with GNU Affero General Public License v3.0 6 votes vote down vote up
shitposting = merge(cloneDeep(jobBase), cloneDeep(jobSingleAction), {
	getters: {
		jobId() {
			return "shitposting";
		},
		baseActions(state, getters, rootState, rootGetters) {
			let actions = cloneDeep(ACTIONS);

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

			for (let action of Object.values(actions)) {
				if (potionItemId == "potionShitposting") {
					action.xp = action.xpActivated;
				} else if (potionItemId == "toolShitposting") {
					action.xp = action.xpActivated*1.5;
				}
			}

			return actions;
		},
		locked(state, getters, rootState, rootGetters) {
			return !rootGetters["upgrades/get"]("shitpostingUnlocked");
		}
	}
})
Example #7
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 #8
Source File: LocaleProvider.jsx    From kube-design with MIT License 6 votes vote down vote up
componentDidMount() {
    const { locales, ignoreWarnings } = this.props;
    const { curLocale } = this.state;
    locale
      .init({
        currentLocale: curLocale,
        locales: merge(defaultLocales, locales),
        ignoreWarnings,
      })
      .then(this.setState({ initDone: true }));
  }
Example #9
Source File: mining.js    From space-station-13-idle with GNU Affero General Public License v3.0 6 votes vote down vote up
mining = merge(cloneDeep(jobBase), cloneDeep(jobSingleAction), {
	getters: {
		jobId() {
			return "mining";
		},
		baseActions(state, getters, rootState, rootGetters) {
			let actions = cloneDeep(ACTIONS);

			let upgradeCount = rootGetters["upgrades/get"]("miningTools");
			let potion = rootGetters["potions/get"]("mining");
			let potionItemId = potion ? potion.itemId : null;

			for (let action of Object.values(actions)) {
				action.time *= 1 / (1 + MINING_UPGRADE_PERCENT * upgradeCount);

				if (potionItemId == "potionMining") {
					let originalItem = action.item;
					delete action.item;
					action.name = ITEMS[originalItem].name

					let newDropTable = cloneDeep(potionDropTable);
					newDropTable.unshift({ chance: 1, item: originalItem })
					action.itemTables = newDropTable;
				} else if (potionItemId == "toolMining") {
					action.xp *= 2;
				}
			}
			return actions;
		}
	}
})
Example #10
Source File: bootstrap.js    From atomize with MIT License 6 votes vote down vote up
createCssRule = ({ propKey, value, props, config }) => {
  const [currentKey, ...otherKeys] = propKey;
  if (!ruleExists(currentKey, config)) return {};
  const { transformer, compose } = hashPropsWithAliases[currentKey];
  const transform = getTransformer(transformer);
  const createCss = (n, key) => {
    const resultValue = trimComma(transformVar(key, transform(n, [])));
    const isValid = typeof resultValue === 'string' ? validate(resultValue) : true;

    if (!isValid) return null;
    return { [key]: resultValue };
  };
  const css = compose
    ? compose.reduce((acc, composeKey) => {
        const cCss = createCss(value, composeKey);
        return merge(acc, cCss);
      }, {})
    : createCss(value, hashPropsWithAliases[currentKey].name);

  return { propKey: otherKeys, value, css, props, config };
}
Example #11
Source File: chemistry.js    From space-station-13-idle with GNU Affero General Public License v3.0 6 votes vote down vote up
chemistry = merge(cloneDeep(jobBase), cloneDeep(jobSingleAction), {
	getters: {
		jobId() {
			return "chemistry";
		},
		baseActions(state, getters, rootState, rootGetters) {
			let actions = cloneDeep(ACTIONS);

			let upgradeCount = rootGetters["upgrades/get"]("chemDispenser");
			let potion = rootGetters["potions/get"]("chemistry");
			let potionItemId = potion ? potion.itemId : null;

			for (let action of Object.values(actions)) {
				if (action.type == "bases") {
					action.time *= (1 - CHEMISTRY_UPGRADE_PERCENT * upgradeCount);
				}

				if (potionItemId == "potionChemistry") {
					if (getters["level"] < action.requiredLevel) {
						action.requiredLevel = 1;
					} else {
						action.preservePotion = true;
					}
				} else if(potionItemId == "toolChemistry"){
					if(action.items){
						action.items.count *= 2;	
					} else {
						action.preservePotion = true;
					}
				}
			}

			return actions;
		},
		locked(state, getters, rootState, rootGetters) {
			return !rootGetters["upgrades/get"]("chemistryUnlocked");
		}
	}
})
Example #12
Source File: initThemes.js    From matx-react with MIT License 6 votes vote down vote up
function createMatxThemes() {
  let themes = {};

  forEach(themeColors, (value, key) => {
    themes[key] = createTheme(merge({}, themeOptions, value));
  });

  return themes;
}
Example #13
Source File: index.js    From course-manager with MIT License 6 votes vote down vote up
// ----------------------------------------------------------------------

export default function ComponentsOverrides(theme) {
  return merge(
    Card(theme),
    Lists(theme),
    Paper(theme),
    Input(theme),
    Button(theme),
    Tooltip(theme),
    Backdrop(theme),
    Typography(theme),
    IconButton(theme),
    Autocomplete(theme)
  );
}
Example #14
Source File: Credential.js    From lens-extension-cc with MIT License 6 votes vote down vote up
/**
   * Converts this API Object into a Catalog Entity Model.
   * @returns {{ metadata: Object, spec: Object, status: Object }} Catalog Entity Model
   *  (use to create new Catalog Entity).
   * @override
   */
  toModel() {
    const model = super.toModel();

    return merge({}, model, {
      metadata: {
        namespace: this.namespace.name,
        labels: {
          [entityLabels.CLOUD]: this.cloud.name,
          [entityLabels.NAMESPACE]: this.namespace.name,
        },
      },
      spec: {
        provider: this.provider,
        region: this.region,
        valid: this.valid,
      },
      status: {
        phase: credentialEntityPhases.AVAILABLE,
      },
    });
  }
Example #15
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 #16
Source File: License.js    From lens-extension-cc with MIT License 6 votes vote down vote up
/**
   * Converts this API Object into a Catalog Entity Model.
   * @returns {{ metadata: Object, spec: Object, status: Object }} Catalog Entity Model
   *  (use to create new Catalog Entity).
   * @override
   */
  toModel() {
    const model = super.toModel();

    return merge({}, model, {
      metadata: {
        namespace: this.namespace.name,
        labels: {
          [entityLabels.CLOUD]: this.cloud.name,
          [entityLabels.NAMESPACE]: this.namespace.name,
        },
      },
      status: {
        phase: licenseEntityPhases.AVAILABLE,
      },
    });
  }
Example #17
Source File: AppCurrentVisits.js    From course-manager with MIT License 6 votes vote down vote up
export default function AppCurrentVisits() {
  const theme = useTheme();

  const chartOptions = merge(BaseOptionChart(), {
    colors: [
      theme.palette.primary.main,
      theme.palette.info.main,
      theme.palette.warning.main,
      theme.palette.error.main
    ],
    labels: ['America', 'Asia', 'Europe', 'Africa'],
    stroke: { colors: [theme.palette.background.paper] },
    legend: { floating: true, horizontalAlign: 'center' },
    dataLabels: { enabled: true, dropShadow: { enabled: false } },
    tooltip: {
      fillSeriesColor: false,
      y: {
        formatter: (seriesName) => fNumber(seriesName),
        title: {
          formatter: (seriesName) => `#${seriesName}`
        }
      }
    },
    plotOptions: {
      pie: { donut: { labels: { show: false } } }
    }
  });

  return (
    <Card>
      <CardHeader title="Current Visits" />
      <ChartWrapperStyle dir="ltr">
        <ReactApexChart type="pie" series={CHART_DATA} options={chartOptions} height={280} />
      </ChartWrapperStyle>
    </Card>
  );
}
Example #18
Source File: SshKey.js    From lens-extension-cc with MIT License 6 votes vote down vote up
/**
   * Converts this API Object into a Catalog Entity Model.
   * @returns {{ metadata: Object, spec: Object, status: Object }} Catalog Entity Model
   *  (use to create new Catalog Entity).
   * @override
   */
  toModel() {
    const model = super.toModel();

    return merge({}, model, {
      metadata: {
        namespace: this.namespace.name,
        labels: {
          [entityLabels.CLOUD]: this.cloud.name,
          [entityLabels.NAMESPACE]: this.namespace.name,
        },
      },
      spec: {
        publicKey: this.publicKey,
      },
      status: {
        phase: sshKeyEntityPhases.AVAILABLE,
      },
    });
  }
Example #19
Source File: enrollmentReducer.js    From datapass with GNU Affero General Public License v3.0 5 votes vote down vote up
globalUpdate = ({ previousEnrollment, futureEnrollment }) =>
  merge(
    {},
    previousEnrollment,
    omitBy(futureEnrollment, (e) => e === null) // do not merge null properties, keep empty string instead to avoid controlled input to switch to uncontrolled input
  )
Example #20
Source File: definition.js    From jafar with MIT License 5 votes vote down vote up
function createSettings(initialSettings) {
  return merge(cloneDeep(settings), initialSettings || {});
}
Example #21
Source File: config.js    From covince with MIT License 5 votes vote down vote up
createConfig = (userConfig) => {
  const config = {}
  merge(config, defaults, userConfig)

  // normalise options
  const { map, timeline, colors, parameters, charts, chart_tooltip } = config
  if (typeof timeline.date_format === 'string') {
    timeline.date_format = {
      heading: timeline.date_format,
      mobile_nav: timeline.date_format,
      chart_tooltip: timeline.date_format
    }
  }
  if (typeof timeline.frame_length !== 'number') {
    timeline.frame_length = 100
  }
  if (typeof map.settings.default_color_by !== 'string') {
    map.settings.default_color_by = userConfig.parameters[0].id
  }
  if (typeof colors === 'undefined') {
    config.colors = defaultColours
  }
  for (const parameter of parameters) {
    if (typeof parameter.precision === 'number') {
      parameter.precision = {
        mean: parameter.precision,
        range: parameter.precision
      }
    }
  }
  if (typeof chart_tooltip === 'object') {
    config.chart.settings.tooltip = {
      ...chart_tooltip
    }
  }
  if (Array.isArray(charts)) {
    config.chart.definitions = charts
  }
  return config
}
Example #22
Source File: mergeData.js    From covid with GNU General Public License v3.0 5 votes vote down vote up
mergeData = (featureCollection, featureCollectionJoinCol, joinData, joinDataNames, joinDataCol) => {
    // declare parent dictionaries
    let features = {}
    let dataDict = {}
    
    // declare and prep feature collection object
    let i = featureCollection.features.length;
    let colNumCheck = parseInt(featureCollection.features[0].properties[featureCollectionJoinCol])
    if (Number.isInteger(colNumCheck)) {
      while (i>0) {
        i--;
        features[parseInt(featureCollection.features[i].properties[featureCollectionJoinCol])] = featureCollection.features[i];
        dataDict[parseInt(featureCollection.features[i].properties[featureCollectionJoinCol])] = {};
      }
    } else {
      while (i>0) {
        i--;
        features[featureCollection.features[i].properties[featureCollectionJoinCol]] = featureCollection.features[i];
        dataDict[featureCollection.features[i].properties[featureCollectionJoinCol]] = {};
      }
    }
  
    // // declare data objects
    // for (let n=0; n < joinDataNames.length; n++) {
    //   dataDict[`${joinDataNames[n]}`] = {}
    // }
  
    // loop through data and add to dictionaries
    let n = joinData.length;
    while (n>0) {
      n--;
      let cols = Object.keys(joinData[n][0]);
      i = cols.length;
      while (i>0) {
        i--;
        try {
          dataDict[cols[i]][joinDataNames[n]] = joinData[n][0][cols[i]]
        } catch {}
      }
    }
    
    // // use lodash to merge data
    let merged = merge(features, dataDict)
    // for (let n=1; n < joinDataNames.length; n++){
    //   merged = merge(merged, dataDict[joinDataNames[n]])
    // }
    
    // clean data
    let rtn = [];
    let keys = Object.keys(merged)
    
    for (let i = 0; i < keys.length; i++) {
      // if (Object.keys(merged[keys[i]]).length == (joinDataNames.length+baseColumnLength)) rtn.push(merged[keys[i]])
      rtn.push(merged[keys[i]])
    }

    return rtn;
}
Example #23
Source File: editor-themes.js    From iceberg-editor with GNU General Public License v2.0 5 votes vote down vote up
EditorThemes = merge( {}, EditorThemes, customThemes );
Example #24
Source File: index.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
defineOptions(options) {
    merge(this.options, options);
  }
Example #25
Source File: ModifiedAreaChart.jsx    From matx-react with MIT License 5 votes vote down vote up
ModifiedAreaChart = ({ height, option }) => {
    return (
        <ReactEcharts
            style={{ height: height }}
            option={merge({}, defaultOption, option)}
        />
    )
}
Example #26
Source File: bootstrap.js    From atomize with MIT License 5 votes vote down vote up
createOverriderStyles = overriders => props =>
  overriders.reduce((acc, ov) => merge(acc, ov(props)), {})
Example #27
Source File: AdvanceAreaChart.jsx    From matx-react with MIT License 5 votes vote down vote up
AdvanceAreaChart = ({ height, option }) => {
  return <ReactEcharts style={{ height: height }} option={merge({}, defaultOption, option)} />;
}
Example #28
Source File: ling.js    From space-station-13-idle with GNU Affero General Public License v3.0 5 votes vote down vote up
ling = merge(cloneDeep(jobBase), cloneDeep(jobSingleAction), {
	getters: {
		jobId() {
			return "ling";
		},
		baseActions(state, getters, rootState, rootGetters) {
			let actions = cloneDeep(ACTIONS);

			let upgradeCount = rootGetters["upgrades/get"]("antagUpgrade");
			let potion = rootGetters["potions/get"]("ling");
			let potionItemId = potion ? potion.itemId : null;

			for (let action of Object.values(actions)) {
				// Apply upgrades
				action.time *= 1 / (1 + ANTAG_UPGRADE_PERCENT * upgradeCount);

				if (potionItemId == "potionLing") {
					Object.keys(action.requiredItems).forEach(key => {
						if (key.toLowerCase().includes('meat')) {
							action.requiredItems[key] -= 1;
							if (action.requiredItems[key] == 0) delete action.requiredItems[key];
						}
					});
					if (Object.values(action.requiredItems).length == 0) {
						delete action.requiredItems;
					}
				} else if(potionItemId == "toolLing"){
					if(action.itemTables){
						if(action.itemTables[0].itemTable[2]){
							let newOutput = action.itemTables[0].itemTable[2].id;
							delete action.itemTables;
							action.item = newOutput;
						} else {
							action.preservePotion;
						}
					} else{
						action.preservePotion;
					}
				}
			}
			return actions;
		},
		locked(state, getters, rootState, rootGetters) {
			return !rootGetters["upgrades/get"]("lingUnlocked");
		}
	}
})
Example #29
Source File: Cluster.js    From lens-extension-cc with MIT License 5 votes vote down vote up
/**
   * Converts this API Object into a Catalog Entity Model.
   * @param {string} kubeconfigPath Path to the cluster's kube config file.
   * @returns {{ metadata: Object, spec: Object, status: Object }} Catalog Entity Model
   *  (use to create new Catalog Entity).
   * @override
   */
  toModel(kubeconfigPath) {
    const model = super.toModel();

    DEV_ENV && rtv.verify({ kubeconfigPath }, { kubeconfigPath: rtv.STRING });

    // NOTE: only add a label if it should be there; adding a label to the object
    //  and giving it a value of `undefined` will result in the entity getting
    //  a label with a value of "undefined" (rather than ignoring it)
    const labels = {
      [entityLabels.CLOUD]: this.cloud.name,
      [entityLabels.NAMESPACE]: this.namespace.name,
    };

    if (this.isMgmtCluster) {
      labels[entityLabels.IS_MGMT_CLUSTER] = 'true';
    }

    if (this.sshKeys.length > 0) {
      // NOTE: this mostly works, but it's a __Lens issue__ that you then have to
      //  search for the combined string, and you can't find all clusters that have
      //  one or the other
      labels[entityLabels.SSH_KEY] = this.sshKeys
        .map(({ name }) => name)
        .join(',');
    }

    if (this.credential) {
      labels[entityLabels.CREDENTIAL] = this.credential.name;
    }

    if (this.proxy) {
      labels[entityLabels.PROXY] = this.proxy.name;
    }

    if (this.license) {
      labels[entityLabels.LICENSE] = this.license.name;
    }

    return merge({}, model, {
      metadata: {
        namespace: this.namespace.name,
        labels,
      },
      spec: {
        kubeconfigPath,
        kubeconfigContext: this.contextName, // must be same context name used in file
        isMgmtCluster: this.isMgmtCluster,
        ready: this.ready,
        apiStatus: this.status,
        controllerCount: this.controllers.length,
        workerCount: this.workers.length,
        region: this.region,
        provider: this.provider,
        currentVersion: this.currentVersion,
        dashboardUrl: this.dashboardUrl,
        lma: this.lma,
      },
      status: {
        // always starts off disconnected as far as Lens is concerned (because it
        //  hasn't loaded it yet; Lens will update this value when the user opens
        //  the cluster)
        phase: clusterEntityPhases.DISCONNECTED,
      },
    });
  }