easy-copy
Copy some properties of an object easily 中文文档
Install
By npm
$ npm install easy-copy
By bower
$ bower install easy-copy
Usage
easyCopy(src [, filter [, opt]])
src
: The source object, where all of the props comes fromfilter
: The filter condition, it could be aString
,Array
, or anObject
, and they could be nested deeplyopt
: The options for copy operation
Get Start
If you often write some code like this:
const data = name: bodyname age: bodyage major: bodymajor email: bodyemail
You must fell tired very much. How can we do if we use easy-copy?
// Import easy-copy moduleconst easycopy = ; const data = ;// Yes! Just write an array :)
Deeply copy
If an object is nested like this:
const foo = id: 1 children: id: 2 children: id: 3 children: id: 4 children: id: 5 children: id: 6 children:
We can process this object easily using easy-copy. For example, if we just want to keep the second property of the children property, we can do like this:
const bar = console;// {// children: [// {// id: 3,// children: [// { id: 4: children: [] },// { id: 5: children: [] }// ]// }// ]// }
OK, but if I want copy the 2 properties which id is 4 and 5, how can I do? You can write like this:
const baz = ; console;// {// children: [// {// children: [// { id: 4, children: [] }// ]// },// { id: 6, children: [] }// ]// }
Yeah! It's so easy!
Options
The third argument of easycopy()
is options. At present, the v1.0
version is support only one option: undefined
.
it could transform the non existed prop of src object set to undefined
automatically. The default value is true
,
in other words, it relay on the filter argument to set the target properties.
Here are some example:
const foo = a: 1 b: 2 c: d: 1 e: 2 const bar = ;// {// c: {// d: 1,// z: undefined// },// f: {// h: unfined// }// } const baz = ;// {// c: {// d: 1,// },// }
So you can decide how to filter and copy an object by your self, and you will not meet with some error
like Cannot read property 'xxx' of undefined
, it is so nasty, isn't it?