@cookbook/dot-notation

Object readings and complex transformations using dot notation syntax.


Keywords
library, javascript
License
MIT
Install
npm install @cookbook/dot-notation@1.1.0

Documentation

@cookbook/dot-notation

Object readings and complex transformations made easy by using dot.notation.syntax[]

NPM Version CI Status Downloads Stats GitHub stars Known Vulnerabilities GitHub issues Awesome install size gzip size

Demo

Play around with dot-notation and experience the magic!

Edit @cookbook/dot-notation

Installation

npm install @cookbook/dot-notation --save
#or
yarn add @cookbook/dot-notation

How to use

Picking a value

import dot from '@cookbook/dot-notation';

const source = {
  person: {
    name: {
      firstName: 'John',
      lastName: 'Doe'
    },
    address: [
      {
        street: 'Infinite Loop',
        city: 'Cupertino',
        state: 'CA',
        postalCode: 95014,
        country: 'United States'
      },
    ]
  }
};

dot.pick(source, 'person.name');
//outputs { firstName: 'John', lastName: 'Doe' }

dot.pick(source, 'person.address[0].street');
//outputs "Infinite Loop"

Parsing an object

Conventional parsing

import dot from '@cookbook/dot-notation';

const source = {
  'person.name.firstName': 'John',
  'person.name.lastName': 'Doe',
  'person.address[].street': 'Infinite Loop',
  'person.address[].city': 'Cupertino',
  'person.address[].postalCode': 95014,
};

dot.parse(source);

/* outputs
{
  person: {
    name: {
      firstName: 'John',
      lastName: 'Doe',
    },
    address: [
      {
        street: 'Infinite Loop',
        city: 'Cupertino',
        postalCode: 95014,
      },
    ],
  },
}
*/

With nested array

where [n] represents the array index position to insert the element

import dot from '@cookbook/dot-notation';

const source = {
  '[0].street': 'Infinite Loop',
  '[0].city': 'Cupertino',
  '[0].postalCode': 95014,
  '[1].street': '1600 Amphitheatre',
  '[1].city': 'Mountain View',
  '[1].postalCode': 94043,
  '[2][0]': 'hobbies',
  '[2][1][0]': ['coding'],
  '[2][1][1]': ['gaming'],
};

dot.parse(source);

/* outputs
[
 {
  "postalCode": 95014,
  "city": "Cupertino",
  "street": "Infinite Loop"
 },
 {
  "postalCode": 94043,
  "city": "Mountain View",
  "street": "1600 Amphitheatre"
 },
 [
  "hobbies",
  [["coding"],["gaming"]]
 ]
]
*/

Parsing single key

import dot from '@cookbook/dot-notation';

const path = 'person.name';
const value = 'John Doe';

dot.parseKey(path, value);

/* outputs
{
  person: {
    name: 'John Doe',
  },
}
*/