lodash#map JavaScript Examples

The following examples show how to use lodash#map. 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: utils.js    From hzero-front with Apache License 2.0 7 votes vote down vote up
export async function setCondition(dataSet, list, reset) {
  map(list, async (param, index) => {
    const field = dataSet.getField(param.fieldName);
    const lovCode = field.get('lovCode');
    const valueField = field.get('valueField');
    let paramName = param.fieldName;
    if (lovCode) {
      if (!valueField) {
        const config = await Stores.LovCodeStore.fetchConfig(lovCode);
        paramName = config.valueField;
      } else {
        paramName = valueField;
      }
    }
    const params = param.comparator.includes('NULL')
      ? `${paramName},${param.comparator}`
      : `${paramName},${param.comparator},${param.value}`;
    dataSet.setQueryParameter(`search.condition.${index}`, reset ? '' : params);
    dataSet.setQueryParameter(paramName, '');
  });
}
Example #2
Source File: index.js    From agenda with MIT License 6 votes vote down vote up
mapStateToProps = state => {
    const aFields = map(fields, field => ({
        ...field,
        options: getOptions(field.control, state),
        value: fromState.Assignments.getAssignment(field.path)(state)
    }));

    return {
        assignment: fromState.Assignments.getAssignment()(state),
        fields: aFields
    };
}
Example #3
Source File: index.js    From gutenberg-forms with GNU General Public License v2.0 6 votes vote down vote up
export function getAllowedBlocks(type) {
	const prefixed = myAttrs.map((slug) => "cwp/" + slug); // ["cwp/email" , .....];

	if (type === "multiStep") {
		prefixed.push("cwp/form-step");
	}

	return prefixed;
}
Example #4
Source File: TableBlockEdit.jsx    From volto-slate with MIT License 6 votes vote down vote up
/**
   * Insert column before handler. Keeps the selected cell as selected after the
   * operation is done.
   * @returns {undefined}
   */
  onInsertColBefore() {
    const table = this.props.data.table;
    this.props.onChangeBlock(this.props.block, {
      ...this.props.data,
      table: {
        ...table,
        rows: map(table.rows, (row, index) => ({
          ...row,
          cells: [
            ...row.cells.slice(0, this.state.selected.cell),
            emptyCell(table.rows[index].cells[this.state.selected.cell].type),
            ...row.cells.slice(this.state.selected.cell),
          ],
        })),
      },
    });
    this.setState({
      selected: {
        row: this.state.selected.row,
        cell: this.state.selected.cell + 1,
      },
    });
  }
Example #5
Source File: estimated-reading-time.js    From iceberg-editor with GNU General Public License v2.0 6 votes vote down vote up
calculateReadingTime() {
		const { content, blocks } = this.props;
		const words = count( content, 'words', {} );

		let estimated = ( words / 275 ) * 60; //get time on seconds
		if ( blocks ) {
			let i = 12;
			map( blocks, ( block ) => {
				if ( mediaBlocks.includes( block.name ) ) {
					estimated = estimated + i;
					if ( i > 3 ) {
						i--;
					}
				}
			} );
		}
		estimated = estimated / 60; //convert to minutes

		//do not show zero
		if ( estimated < 1 ) {
			estimated = 1;
		}

		return estimated.toFixed();
	}
Example #6
Source File: index.js    From hzero-front with Apache License 2.0 6 votes vote down vote up
/**
   * 渲染表单行
   * @param {Object[]} rowFields - 一行对应的字段
   */
  renderRow({ rowFields }) {
    const { disableStyle } = this.props;
    return (
      <Row
        type="flex"
        key={join(map(rowFields, field => field.fieldCode), '-')}
        className={disableStyle === 'value' ? 'row-disabled' : ''}
      >
        {map(rowFields, field =>
          this.renderComposeFormField({
            field,
            disableStyle,
          })
        )}
      </Row>
    );
  }
Example #7
Source File: RequestsContainer.js    From covidsos with MIT License 6 votes vote down vote up
getFilter(key, name, val_key, mapperFunc = (val) => {
    return (<option key={val} value={val}>{val}</option>);
  }) {
    const {filterData, filters} = this.state
    return (filterData[key] &&
        <Col md={2} xs={6} className="pt-3">
          <InputGroup className="input-group-alternative r-filter">
            <InputGroupAddon addonType="prepend">
              <InputGroupText>
                <i className="fas fa-filter"/>
              </InputGroupText>
            </InputGroupAddon>
            <Input
                placeholder={name}
                type="select"
                value={filters[val_key || key]}
                onChange={e => {
                  let value = e.target.value;
                  this.handleFilter(val_key || key, value);
                }}>
              <option value="">{name}</option>
              <option value="any">Any</option>
              {filterData[key].map(mapperFunc)}
            </Input>
          </InputGroup>
        </Col>);
  }
Example #8
Source File: Fpos.js    From SESTA-FMS with GNU Affero General Public License v3.0 6 votes vote down vote up
fpoDelete(cellid, fpoInUseSingleDelete) {
    this.state.contacts.find((cd) => {
      // check if fpo is present in user's individual
      if (
        cd.individual !== null &&
        cd.individual.fpo !== null &&
        cd.individual.fpo === parseInt(cellid)
      ) {
        fpoInUseSingleDelete = true;
      }
      //check if fpo is present in VO
      if (
        cd.organization !== null &&
        cd.organization.fpo !== null &&
        cd.organization.fpo === parseInt(cellid)
      ) {
        fpoInUseSingleDelete = true;
      }
    });

    // check if fpo is present in loan model
    this.state.loanpurpose.map((loanmodel) => {
      if (loanmodel.fpo !== null) {
        if (loanmodel.fpo.id === parseInt(cellid)) {
          fpoInUseSingleDelete = true;
        }
      }
    });

    //check if fpo is present in activity types
    this.state.activityTypes.map((types) => {
      if (types.contact.length > 0) {
        if (types.contact[0].id === parseInt(cellid)) {
          fpoInUseSingleDelete = true;
        }
      }
    });
    return fpoInUseSingleDelete;
  }
Example #9
Source File: index.js    From certd with MIT License 5 votes vote down vote up
generators = files.keys().map(key => files(key).default)
Example #10
Source File: formulaBuilder.js    From gutenberg-forms with GNU General Public License v2.0 5 votes vote down vote up
function FormulaBuilder(prop) {
	const area = useRef();

	const props = prop.data;

	const { clientId } = props,
		{ formula } = props.attributes;

	const addFieldId = (name) => {
		var $txt = $(area.current);
		var caretPos = $txt[0].selectionStart;
		var textAreaTxt = $txt.val();
		var txtToAdd = `{{${name}}}`;

		const val =
			textAreaTxt.substring(0, caretPos) +
			txtToAdd +
			textAreaTxt.substring(caretPos);

		props.setAttributes({ formula: val });
	};

	return (
		<div className="cwp-form-calc-builder">
			<div className="cwp-form-available-fields">
				<h4>{__('Available Number Fields:', 'cwp-gutenberg-forms')}</h4>
				<DropdownMenu icon="list-view" label={__("Add Field Data", 'cwp-gutenberg-forms')}>
					{({ onClose }) => (
						<Fragment>
							<MenuGroup>
								{map(getSiblings(clientId, "cwp/number"), (field) => {
									const { field_name, label } = field;

									return (
										<MenuItem
											icon={getFieldIcon("cwp/number")}
											onClick={() => {
												onClose();
												addFieldId(field_name);
											}}
										>
											<span
												draggable={true}
												dangerouslySetInnerHTML={{ __html: label }}
											></span>
										</MenuItem>
									);
								})}
							</MenuGroup>
						</Fragment>
					)}
				</DropdownMenu>
			</div>
			<textarea
				value={formula}
				onChange={(e) => props.setAttributes({ formula: e.target.value })}
				ref={area}
			></textarea>
		</div>
	);
}
Example #11
Source File: index.js    From django-vue-admin-pro with Apache License 2.0 5 votes vote down vote up
generators = files.keys().map(key => files(key).default)
Example #12
Source File: TableBlockEdit.jsx    From volto-slate with MIT License 5 votes vote down vote up
emptyRow = (cells) => ({
  key: getId(),
  cells: map(cells, () => emptyCell()),
})
Example #13
Source File: handle-menu-item.js    From horondi_admin with MIT License 5 votes vote down vote up
handleMenuItem = (materials) =>
  map(materials, (item, index) => (
    <MenuItem value={item._id} key={item.name[1].value}>
      {item.name[0].value}
    </MenuItem>
  ))
Example #14
Source File: use-product-filters.js    From horondi_client_fe with MIT License 5 votes vote down vote up
useProductFilters = (filterParams, filtersList) => {
  const { search } = useLocation();
  const { t, i18n } = useTranslation();
  const history = useHistory();
  const [filtersData, setFiltersData] = useState({});
  const { page, defaultPage } = URL_QUERIES_NAME;

  const searchParams = new URLSearchParams(search);

  const language = i18n.language === 'ua' ? 0 : 1;
  const filterNames = ['category', 'models', 'patterns'];
  const queriesNames = [
    URL_QUERIES_NAME.categoryFilter,
    URL_QUERIES_NAME.modelsFilter,
    URL_QUERIES_NAME.patternsFilter
  ];

  const handleFilterChange = ({ target }, queryName, categoriesList) => {
    const query = searchParams.get(queryName) || '';
    const currentCategory = categoriesList.find((el) => el.name[language].value === target.name);

    target.checked
      ? searchParams.set(queryName, query.concat(',', currentCategory._id))
      : searchParams.set(queryName, query.replace(`,${currentCategory._id}`, ''));

    searchParams.set(page, defaultPage);
    history.push(`?${searchParams.toString()}`);
  };

  useEffect(() => {
    const data = {};

    Object.keys(filtersList).forEach((key, index) => {
      data[key] = {
        filterName: t(`common.${filterNames[index]}`),
        productFilter: filterParams[filterNames[index]] || [],
        list: map(filtersList[key], (el) => el.name[language].value),
        categories: filtersList[key],
        filterHandler: (e) => handleFilterChange(e, queriesNames[index], filtersList[key])
      };
    });
    setFiltersData(data);
  }, [filtersList, filterParams, language]);

  return filtersData;
}
Example #15
Source File: StatsCell.js    From covid19 with MIT License 5 votes vote down vote up
Success = ({ countries = [], country = 'usa' }) => {
  // Calculate stats
  const [counts, setCounts] = useState([])
  const stat = (key) =>
    commaNumber(last(map(orderBy(counts, 'date.date'), key)))
  useEffect(() => {
    setCounts(find(countries, ['iso', country])?.dailyCounts)
  }, [country])

  return (
    <div>
      <section>
        <StatChart data={counts} dataKey="newCases" color="green" />
        <Stat value={stat('newCases')} label="New cases" />
      </section>
      <section>
        <StatChart data={counts} dataKey="currentlyInfected" color="yellow" />
        <Stat value={stat('currentlyInfected')} label="Currently infected" />
      </section>
      <section>
        <StatChart data={counts} dataKey="totalCases" color="orange" />
        <Stat value={stat('totalCases')} label="Confirmed cases" />
      </section>
      <section>
        <StatChart data={counts} dataKey="totalDeaths" color="red" />
        <Stat value={stat('totalDeaths')} label="Confirmed deaths" />
      </section>
      <style jsx>{`
        div {
          display: grid;
          grid-gap: 1rem;
          margin-top: 2rem;
        }
        @media (min-width: 48em) {
          div {
            grid-template-columns: repeat(4, 1fr);
          }
        }
        section {
          position: relative;
          min-height: 8rem;
        }
        section :global(.recharts-responsive-container) {
          position: absolute !important;
          top: 0;
          left: 0;
          right: 0;
        }
      `}</style>
    </div>
  )
}
Example #16
Source File: index.js    From iceberg-editor with GNU General Public License v2.0 5 votes vote down vote up
render() {
		const {
			isActive,
			allowedBlockTypes,
			blockTypes,
			toggleVisible,
			updateLimitedBlocks,
		} = this.props;

		const disabled = [];
		const hiddenBlocks = [];

		if ( typeof this.props.limitedBlocks === 'undefined' ) {
			return false;
		}

		const limitedBlocks = JSON.parse( this.props.limitedBlocks, true );

		if ( allowedBlockTypes ) {
			allowedBlocks = allowedBlockTypes;
		}

		if ( isActive ) {
			map( blockTypes, ( blockType ) => {
				if (
					! allowedBlocks.includes( blockType.name ) &&
					! hiddenBlocks.includes( blockType.name )
				) {
					disabled.push( blockType.name );
				}
			} );

			if (
				typeof limitedBlocks.length === 'undefined' ||
				limitedBlocks.length === 0
			) {
				toggleVisible( disabled );
				toggleVisible( allowedBlocks, true );
				updateLimitedBlocks( disabled );
			}
		} else if ( ! isActive && limitedBlocks.length > 0 ) {
			toggleVisible( limitedBlocks, true );
			updateLimitedBlocks( {} );
		}

		return false;
	}
Example #17
Source File: BaseComposeTable.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
/**
 * 获取计算得来的属性(且耗时多)
 * @param {Object} props
 */
function getNoEditableComputeTableProps(props) {
  const { fields, context } = props;
  // let index = 0;
  let columnsWidth = 0;
  const columns = map(fields, field => {
    // const required = field.requiredFlag !== 0;
    const columnWidth = getWidthFromWord({
      word: field.fieldDescription,
      minWidth: 60,
      fontWidth: 12,
      defaultWidth: 100,
      paddingWidth: 36,
    });
    columnsWidth += columnWidth;
    const column = {
      dataIndex:
        field.componentType === 'ValueList' || field.componentType === 'Lov'
          ? `${field.fieldCode}Meaning`
          : field.fieldCode,
      title: field.fieldDescription,
      width: columnWidth,
    };
    if (field.componentType === 'Checkbox' || field.componentType === 'Switch') {
      column.render = item =>
        item === 1
          ? intl.get('hzero.common.status.yes').d('是')
          : intl.get('hzero.common.status.no').d('否');
    } else if (field.componentType === 'Upload') {
      const uploadProps = getComponentProps({
        field,
        componentType: 'Upload',
        context,
      });
      column.render = item => item && <Upload {...uploadProps} viewOnly attachmentUUID={item} />;
    }
    return column;
  });
  return {
    scroll: { x: columnsWidth },
    columns,
  };
}