data-pattern

1.1.0 • Public • Published

data-pattern

Node version NPM version

Format data in the specific pattern we wanted.

why use data-pattern?

The data we fetch from the server may not be what we expected. We need a simple way to unify the data format.

const dataPattern = require('data-pattern');
 
ajax.get('/persons')
    .then((data) => {
        return dataPattern(data, []);
    });

Installation

npm install data-pattern

Usage

Expect data to be array:

dataPattern(data, []);

Expect data to be object:

dataPattern(data, {});

Format every item of array:

dataPattern(data, [{
    children: []
}]);
dataPattern(data, [[]]);

Format value of object:

dataPattern(data, {
    info: {},
    children: []
});

Pattern can be a function which accepts current data as first arguments:

dataPattern(data, (item) => {
    return item.sort((a, b) => b.item - a.item);
});

Format function for array items:

dataPattern(data, [(item) => {
    return {
        level: item.level - 1
    };
}]);

Below is equal:

dataPattern(data, {
    children: [{
        info: {}
    }]
});
 
// is equal to
 
dataPattern(data, {
    children: (children) => {
        if (!children) {
            return []
        }
 
        return children.map((item) => dataPattern(item, {
            info: {}
        }));
    }
});

Use strict mod to filter properties:

let data = {
    name: 'lxjwlt',
    map: {}
};
 
dataPattern.strict(data, {
    name: true,
    list: []
});
 
/*
{
    name: 'lxjwlt',
    list: []
}
*/

A quick example:

const dataPattern = require('data-pattern');
 
let data = {
    children: [null, {}],
    map: {
        shouldBeKeep: 0
    },
    timestamp: 1487504955 // in seconds
};
 
let pattern = {
    children: [{
        info: {}
    }],
    map: {
        arr: []
    },
    timestamp: (timestamp) => {
        return timestamp * 1000; // in microseconds
    }
};
 
dataPattern(data, pattern);
 
/*
{
    children: [
        {
            info: {}
        },
        {
            info: {}
        }
    ],
    map: {
        shouldBeKeep: 0,
        arr: []
    },
    timestamp: 1487504955000
}
*/

Readme

Keywords

Package Sidebar

Install

npm i data-pattern

Weekly Downloads

2

Version

1.1.0

License

MIT

Last publish

Collaborators

  • lxjwlt