How to use the flat.flatten function in flat

To help you get started, we’ve selected a few flat examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github appirio-tech / connect-app / src / helpers / wizardHelper.js View on Github external
export const buildProjectUpdateQueryByQueryParamSelectCondition = (template, queryParams) => {
  /**
   * Supported types of questions
   */
  const TYPE = {
    CHECKBOX_GROUP: 'checkbox-group',
    RADIO_GROUP: 'radio-group',
  }
  const prefillData = {}
  const updateQuery = { $merge: prefillData }
  const flatQueryParams = flatten(queryParams, { safe: true })

  forEachNode(template, (nodeObject, node) => {
    if (
      // if condition is defined
      nodeObject.queryParamSelectCondition &&
      // support only for `options` nodes
      isNodeLevel(node, LEVEL.OPTION) &&
      // if condition is satisfied
      evaluate(nodeObject.queryParamSelectCondition, flatQueryParams)
    ) {
      const questionNode = getParentNode(node)
      const questionNodeObject = getNodeObject(template, questionNode)

      if (!questionNodeObject.fieldName) {
        console.error('Question of the option with "queryParamSelectCondition" doesn\'t have "fieldName". So we cannot pre-fill data.')
        return
github akameco / extract-react-intl-messages / src / index.ts View on Github external
const file = path.resolve(buildDir, `${locale}.${ext}`)
    // Initialize json file
    try {
      const output = isJson(ext) ? JSON.stringify({}) : yaml.safeDump({})
      fs.writeFileSync(file, output, { flag: 'wx' })
    } catch (error) {
      if (error.code !== 'EEXIST') {
        throw error
      }
    }

    let messages = isJson(ext)
      ? loadJsonFile.sync(file)
      : yaml.safeLoad(fs.readFileSync(file, 'utf8'), { json: true })

    messages = flatten(messages)

    oldLocaleMaps[locale] = {}
    for (const messageKey of Object.keys(messages)) {
      const message = messages[messageKey]
      if (message && typeof message === 'string' && message !== '') {
        oldLocaleMaps[locale][messageKey] = messages[messageKey]
      }
    }
  }

  return oldLocaleMaps
}
github iopipe / iopipe-js-trace / src / plugins / https.js View on Github external
// setup http trace data that will be sent to IOpipe later
      moduleData[id] = {};
      moduleData[id].request = getReqDataObject(rawOptions, protocol);
      // patch for Axios
      if (!moduleData[id].request.hostname && moduleData[id].request.host) {
        moduleData[id].request.hostname = moduleData[id].request.host;
      } else if (
        !moduleData[id].request.hostname &&
        moduleData[id].request.url
      ) {
        moduleData[id].request.hostname = moduleData[id].request.url;
      }

      // flattening so that req headers can be sent even if there's a timeout
      moduleData[id] = flatten(moduleData[id], { maxDepth: 5 });
      moduleData[id] = filterData(config, moduleData[id]);

      // the func to execute at the end of the http call
      function extendedCallback(res) {
        timeline.mark(`end:${id}`);
        // add full response data if the request passed filtering
        if (typeof moduleData[id] === 'object') {
          moduleData[id].response = getResDataObject(res);
          // flatten object for easy transformation/filtering later
          moduleData[id] = flatten(moduleData[id], { maxDepth: 5 });
          moduleData[id] = filterData(config, moduleData[id]);
        }

        // if either filter function returns falsey value, drop all data completely
        if (typeof moduleData[id] !== 'object') {
          timeline.data = timeline.data.filter(
github commercetools / nodejs / packages / discount-code-exporter / src / main.js View on Github external
// fields if empty and they are not correctly written to the CSV file
    const objKeys = [
      'attributeTypes',
      'cartFieldTypes',
      'lineItemFieldTypes',
      'customLineItemFieldTypes',
    ]

    const discountCodeData = Object.entries(restDiscountCodeData).reduce(
      (discountCode: Object, [discountCodeKey, value]: [string, any]): Object =>
        objKeys.includes(discountCodeKey) && !Object.entries(value).length
          ? discountCode
          : { ...discountCode, [discountCodeKey]: value },
      {}
    )
    return flatten({
      ...discountCodeData,
      cartDiscounts: cartDiscountsString,
      groups: groupsString,
    })
  }
}
github DefinitelyTyped / DefinitelyTyped / types / flat / flat-tests.ts View on Github external
a: {
			b: number;
		},
		c: boolean[][];
	};

	let target: Target;

	type Result = {
		'a.b': number;
		'c.0.0': boolean;
	};

	let result: Result;

	result = flatten(target);
	result = flatten(target, options);
}

namespace TestUnflatten {
	let options: {
		delimiter?: string;
		object?: boolean;
		overwrite?: boolean;
	};

	type Target = {
		'a.b': number;
		'c.0.0': boolean;
	};

	let target: Target;
github DonJayamanne / pythonVSCode / gulpfile.js View on Github external
function hasNativeDependencies() {
    let nativeDependencies = nativeDependencyChecker.check(path.join(__dirname, 'node_modules'));
    if (!Array.isArray(nativeDependencies) || nativeDependencies.length === 0) {
        return false;
    }
    const dependencies = JSON.parse(spawn.sync('npm', ['ls', '--json', '--prod']).stdout.toString());
    const jsonProperties = Object.keys(flat.flatten(dependencies));
    nativeDependencies = _.flatMap(nativeDependencies, item => path.dirname(item.substring(item.indexOf('node_modules') + 'node_modules'.length)).split(path.sep))
        .filter(item => item.length > 0)
        .filter(item => jsonProperties.findIndex(flattenedDependency => flattenedDependency.endsWith(`dependencies.${item}.version`)) >= 0);
    if (nativeDependencies.length > 0) {
        console.error('Native dependencies detected', nativeDependencies);
        return true;
    }
    return false;
}
github madebymany / front-end-london / src / components / Blob / Blob.js View on Github external
generateBlob() {
    const { complexity, contrast, size, seed } = this.props
    const points = blob(complexity, contrast, size, `${seed}${this.counter}`)

    this.counter += 1

    return flatten(points)
  }
github decentraland / agora / scripts / translate.ts View on Github external
async function writeTranslations(
  flatMissingTranslations: TranslationCache,
  basePath: string = '../src/Translation/locales'
) {
  const mainTranslations = await new Translation().fetch(DEFAULT_LOCALE)
  const availableLocales = await getAvailableLocales()

  const flatMainTranslations = flat.flatten(
    mainTranslations
  )

  for (const locale of availableLocales) {
    const localePath = path.resolve(__dirname, `${basePath}/${locale}.json`)
    const flatCurrentTranslations = flatAndRemoveObsoleteKeys(
      require(localePath),
      flatMainTranslations
    )

    let updatedTranslations = Object.assign(
      {},
      flatCurrentTranslations,
      flatMissingTranslations[locale]
    )
    updatedTranslations = flat.unflatten(updatedTranslations)
github decentraland / agora / scripts / translate.ts View on Github external
function flatAndRemoveObsoleteKeys(
  translations: TranslationData,
  flatBaseTranslations: TranslationData
): TranslationData {
  const currentTranslations = flat.flatten(translations)

  const cleanedTranslations = Object.keys(currentTranslations)
    .filter(key => key in flatBaseTranslations)
    .reduce((clean, key) => ({ ...clean, [key]: currentTranslations[key] }), {})

  return cleanedTranslations
}
github appirio-tech / connect-app / src / projects / detail / components / ScopeChangeRequest / ScopeChangeRequest.jsx View on Github external
getDiff(oldScope, newScope) {
    const oldFlatScope = flatten(oldScope, { safe: true })
    const newFlatScope = flatten(newScope, { safe: true })

    return _.omitBy(newFlatScope, (newValue, key) => _.isEqual(oldFlatScope[key], newValue))
  }

flat

Take a nested Javascript object and flatten it, or unflatten an object with delimited keys

BSD-3-Clause
Latest version published 8 months ago

Package Health Score

80 / 100
Full package analysis