1.0.0 • Published 5 years ago

super-deep-pick v1.0.0

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

Deep pick

As you know lodash.pick, so this module like that but DEEEEEEEEEEEEEEEP.

How it work

As you know Facebook API or GraphQL. They developer can pick the fields they want to return

Example for Facebook:

https://graph.facebook.com/v3.1/me?access_token=ACCESS_TOKEN&fields=id,email,name,birthday,first_name,last_name,age_range,link,gender,locale,picture,timezone,updated_time,verified

So when you use this module, you can handle this very easy:

const deepPick = require('deepPick');
const data = 'Array or Object';
const fields = request.query.fields.split(',');

return deepPick(data, fields);

Why we dont use Lodash.pick

Because lodash.pick only work with level 1 of object, not pick deep like GraphQL

Example

const deepPick = require('deepPick');

const data = {
  id: 1,
  title: 'Level 1',
  level1: {
    data1: [
      {
        level2: {
          level3: {
            id: 3,
            title: 'Level 3',
            data3: [
              'foo',
              'bar'
            ],
            level4: {
              id: 4,
              title: 'Level 4',
              data4: [
                'foo2',
                'bar2'
              ],
            },
            exclude: 'not return'
          }
        }
      }
    ]
  },
  exclude: 'not return'
};

// User [] to easy understand data structure
const fields1 = [
  'id',
  'title',
  'level1.data1[].level2.level3.id',
  'level1.data1[].level2.level3.title',
  'level1.data1[].level2.level3.data3[]',
  'level1.data1[].level2.level3.level4.data4[]',
];

// not use [], but everything work
const fields2 = [
  'id',
  'title',
  'level1.data1.level2.level3.id',
  'level1.data1.level2.level3.title',
  'level1.data1.level2.level3.data3',
  'level1.data1.level2.level3.level4.data4',
];

console.log(JSON.stringify(deepPick(data, fields1), null, 2));
console.log(JSON.stringify(deepPick(data, fields2), null, 2));

Result data

{
  "id": 1,
  "title": "Level 1",
  "level1": {
    "data1": [
      {
        "level2": {
          "level3": {
            "id": 3,
            "title": "Level 3",
            "data3": [
              "foo",
              "bar"
            ],
            "level4": {
              "data4": [
                "foo2",
                "bar2"
              ]
            }
          }
        }
      }
    ]
  }
}

Testing

Clone project

git clone git@github.com:kimthangatm/deep-pick.git
cd deep-pick

Run test or test coverage

npm run test
npm run test:coverage
# or
yarn test