Skip to content

lxjwlt/data-pattern

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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, (persons) => {
    return persons.sort((a, b) => b.age - a.age);
});

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
}
*/

About

Format data in the specific pattern we wanted.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published