Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including data-refactor with all npm packages installed. Try it out:

var dataRefactor = require("data-refactor")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

data-refactor v0.1.3

refactor data structure

data-refactor

数据格式化

用于前后端分离的 web 项目的接口字段格式化

install

npm i data-refactor

usage

refactor(tar, rule [, strict = true])

import refactor from 'data-refactor';

const tar = {
  pic: 'https://unsplash.it/800/800/?random',
  nick_name: 11,
  age: '13',
  is_adult: 1,
  obj: {
    opt1: 1,
    opt2: 'dsds',
  },
  postscript: [
    {
      ps_id: '11',
      ps_name: 'sth11',
    },
    {
      ps_id: 12,
      ps_name: 'sth12',
    },
  ],
  deepArr: [
    [
      { da_id: 1, da_name: '1', da_other: 'ss' },
      { da_id: 2, da_name: '2', da_other: 'ss' },
    ],
    [{ ea_id: 1, ea_name: '1' }, { ea_id: 2, ea_name: '2' }],
    [{ fa_id: 1, fa_name: '1' }, { fa_id: 2, fa_name: '2' }],
  ],
};

const rule = {
  avatar: 'pic',

  nickname1: 'nick_name|String',
  nickname2: 'nick_name|string',
  nickname3: 'nick_name|str',

  age1: 'age|Number',
  age2: 'age|number',
  age3: 'age|num',

  isAdult1: 'is_adult|Boolean',
  isAdult2: 'is_adult|boolean',
  isAdult3: 'is_adult|bool',

  obj: {
    p1: 'opt1|num',
    p2: 'opt2',
  },

  o: 'obj',
  _o: {
    p1: 'opt1|num',
    p2: 'opt2',
  },

  ps1: 'postscript',

  ps2: 'postscript',
  _ps2: [
    {
      id: 'ps_id',
      name: 'ps_name',
    },
  ],

  da: 'deepArr',
  deepArr: [
    [
      {
        id: 'da_id|bool',
        name: 'da_name',
      },
    ],
    [
      {
        id: 'ea_id',
        name: 'ea_name',
      },
    ],
    [
      {
        id: 'fa_id',
        name: 'fa_name',
      },
    ],
  ],
};

const strict = !0;

const resStrict = refactor(tar, rule, strict);

params

  • tar

    • 操作对象
  • rule

    • 格式化规则
  • strict 是否严格格式化

    • 默认 false
    • 严格格式化所得结果与 rule 完全一致, 不含无用字段

suport

格式化数据

key|type

  • Number|number|num
  • String|string|str
  • Boolean|boolean|bool

操作符

  • _ 对象或数组的内部映射
  • | 类型分割符
  • . 属性运算符

后续优化

  • 支持函数规则
  • 支持修改预设操作符 _ | .

Metadata

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free