Format data in the specific pattern we wanted.
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, []);
});
npm install data-pattern
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
}
*/