normalize-type

2019-11-22 admin

normalize-type是什么

什么是normalize-type,Normalizes string JavaScript values to have real type (so "123" becomes number 123 etc).

normalize-type使用教程帮助文档

Normalize type

Coverage Downloads Version License

Normalizes string JavaScript values to have real type.

  • a string "123" becomes number 123.
  • "true" becomes boolean true.
  • works recursively on objects and as well so { a: ['123'] } becomes { a: [123] } etc.

Mainly useful for parsing query parameters etc where you always get string values for everything but you’d like to use the values with their real types or validate them etc.

Installation

This package is distributed via npm

npm install normalize-type

Example

const normalizeType = require('./build/index').default;

const parameters = {
  id: '2',
  name: 'Jack Daniels',
  age: '26',
  height: '1.84',
  birthday: new Date(1849, 1, 15, 0, 0, 0, 0),
  accessLevels: ['1', '3'],
};

console.log(normalizeType(parameters));

/*
> npm run build && node example
{
  id: 2,
  name: 'Jack Daniels',
  age: 26,
  height: 1.84,
  birthday: 1849-02-14T22:00:00.000Z,
  accessLevels: [ 1, 3 ]
}
*/

See example.js and run npm run build && node example to try for yourself.

Features verified by 100% test coverage

  • √ should leave strings to be strings (3ms)
  • √ should not modify non-strings (2ms)
  • √ should convert numeric integer strings to numbers
  • √ should convert numeric float strings to numbers
  • √ should preserve number-like invalid number values (1ms)
  • √ should convert “true” and “false” to booleans
  • √ should convert “undefined” to undefined
  • √ should not convert non-lowercase special mappings
  • √ should convert arrays of values (1ms)
  • √ should convert nested arrays of values
  • √ should convert object maps (1ms)
  • √ should convert nested object maps
  • √ should handle mixed content

本站文章除注明转载外,均为本站原创或编译。欢迎任何形式的转载,但请务必注明出处。

转载请注明:文章转载自 JavaScript中文网 [https://www.javascriptcn.com]

本文地址:https://www.javascriptcn.com/read-79659.html

文章标题:normalize-type

回到顶部