JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 9
  • Score
    100M100P100Q43695F
  • License MIT

Implements array-like methods for Object with support for dot notation keys

Package Exports

  • dot-object-array

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (dot-object-array) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

GitHub release Build Status Coverage Status semantic-release

bitHound Overall Score bitHound Code bitHound Dependencies bitHound Dev Dependencies Known Vulnerabilities

Liqueur de Toile

DotObjectArray, a.k.a. DOA a.k.a. ObjectArray

Why DOA ?

For three reasons :

  • No support for associative arrays in vanilla JS
  • Creating deep levels keys in a vanilla JS Object can programmatically be a pain if none of parent keys exists
  • Bored of always using the same snippets everywhere and wants to have a less then 10KB NPM dependency ready to import

Features

DOA is an object with a set of methods to :

  • Check, push, get and store data with ease regardless of its level
  • Brings some array-like behaviours for convenience (you know forEach, eh ?)
  • Easy to use data serializers and parsers
  • Work as well on a whole dataset or a key-based sub-selection of the dataset

Quick examples

// Import data at creation
var doa = new ObjectArray({
    item1: 3,
 item2: 12,
 item3: 5
});

//Add data
doa.push('item4', 4); // Single item or dataset
doa.import({
  item5: 5,
  item6: 6
});

//Add data with dotted notations
doa.push('dat.long.darn.key','isntIt?'); // Will automatically create each keys

//Iterate on keys at root level or in sub dataset
doa.forEach(function(value, key, index) {
 [...]
});
doa.forEach(function(value, key, index) {
 [...]
}, 'dat.path.to.data');

// Sub dataset import
doa.import({
 subitem1: 1,
 subitem2: 'astring',
 subitem3: {obj: really}
}, 'dat.long.and.far.away.key');

sub dataset access
doa.dataset('dat.long.and.far.away.key');

//
And many more !

Playground

If you want to go further and try a bit, you can go to the playground.

Table of contents

Install

Module

The ObjectArray class is provided as a UMD module available on NPM.

npm install dot-object-array

Then simply require/import it :

import ObjectArray from 'dot-object-array';
const ObjectArray = require('dot-object-array').default;

ObjectArray have been built on a ECMA6 class with a default export. that's the reason why one must append default to the require call.

Browser

For browser install, you can simply fetch dist/objectarray.min.js in this repo and load it :

<script type="text/javascript" src="myJsFolder/objectarray.min.js"></script>

An ObjectArray constructor will be added to global (window) scope.

Usage

Api details

A full documentation for Api is available on two formats :

Create an instance

You can create an instance by calling new ObjectArray() or initialize it with data at creation :

// Vanilla object
var test = {
  test1: 'fixture',
  test2: {
    subtest1: 'subfixture1',
    subtest2: 'subfixture2'
  }
};

var doa = new ObjectArray(test);

Data managemement

Raw data getter and setter

The whole data object will be accessible and mutable through the data property :

var doa = new ObjectArray();
// Set the data
doa.data = {test: 'fixture'};
// Get the data
console.log(doa.data.test) //Output 'fixture'

You can only treat with the whole data object through this property. Data is kept under a "private" _data property that can be accessed though I do not recommend it, especially for imports

Fetch dataset

Specific dataset linked to a key can be retrieved with the dataset method (or its alias pull method) and using dot notation :

var doa = new ObjectArray({
  dat: {
    long: {
      path: 'fixture1',
      dream: 'fixture2'
    }
  }
});

// Get the dataset
console.log(doa.dataset('dat.long')) //Output {path: 'fixture1', dream: 'fixture2'}
// or
console.log(doa.pull('dat.long')) //Output {path: 'fixture1', dream: 'fixture2'}

Calling doa.dataset() will return the whole data object.

Using doa.dataset('dat.stupid.path.to.things') will return undefined because keys don't exist, while doa.data.dat.stupid.path.to.things will throw an error.

Push data

As an array, you can push data by calling the push method of the ObjectArray. You can use dotted key notation and ObjectArray will take care to create all needed keys.

var doa = new ObjectArray();
doa.push('dat.really.long.path', 'fixture');
console.log(doa.data);
// will output {dat:{really:{long:{path:"fixture"}}}}

You can safely import or push an ObjectArray into another ObjectArray at any level. The data will be safe.

Import data

If you want to import multiple keys at once, you can do only one call to import :

var doa = new ObjectArray();
doa.import({
  'dat.really.long.path', 'fixture1',
  'dat.really.long.dream', 'fixture2',
  'dat.shorter.path', 'fixture3'
);
console.log(doa.data);
// will output {dat:{really:{long:{path:"fixture1",dream:"fixture2"}},shorter:{path:"fixture3"}}}

You can safely import or push an ObjectArray into another ObjectArray at any level. The data will be safe.

Push and import in dataset

You can easily push or import in dataset with an extra parameter.

var doa = new ObjectArray();
doa.push('dat.really.long.path', 'fixture1');
doa.push('dream', 'fixture2', 'dat.really.long');
doa.import({
  'shorter.path': 'fixture3'
}, 'dat');

console.log(doa.data);
// will output {dat:{really:{long:{path:"fixture1",dream:"fixture2"}},shorter:{path:"fixture3"}}}

You can safely import or push an ObjectArray into another ObjectArray at any level. The data will be safe.

Empty data and remove dataset

To remove the data linked to a key, simply call remove method while providing the key to delete

var doa = new ObjectArray({
  dat: {
    long: {
      path: 'fixture1',
      dream: 'fixture2'
    }
  }
});

// Delete dat.long.path
doa.remove('dat.long.dream');

console.log(doa.dataset('dat.long')) //Output {path: 'fixture1'}

Wider, the empty method is an alias to remove method if a key is provided but completely empty ObjectArray data if called without parameter.

Utility methods

Check key existence

Use the has method

var doa = new ObjectArray({
  dat: {
    long: {
      path: 'fixture1',
      dream: 'fixture2'
    }
  }
});

doa.has('dat.long.path'); // returns true
doa.has('dat.short.path'); // returns false

get length of a dataset

Use the length method with the key of the dataset. Providing no key means to be the top-level of the data object.

var doa = new ObjectArray({
  dat: {
    long: {
      path: 'fixture1',
      dream: 'fixture2'
    }
  }
});

doa.length(); // returns 1 (one key in the dataset : dat
doa.length('data.long'); // returns 2 (two keys in the dataset : path and dream

The method will return undefined if the key doesn't exist.

Get array of keys or array of values of a dataset

Use the keys or values method with the key of the dataset. Providing no key means to be the top-level of the data object.

var doa = new ObjectArray({
  dat: {
    long: {
      path: 'fixture1',
      dream: 'fixture2'
    }
  }
});

doa.keys(); // returns ['dat']
doa.values(); // returns [{long:{path:'fixture1', dream:'fixture2'}}], not very useful in this case
doa.keys('dat.long'); // returns ['path','dream']
doa.values('dat.long'); // returns ['fixture1','fixture2']

The methods will return undefined if the key doesn't exist.

Flatten data and datasets

You can use the flatten method to flatten all underlying data levels to the root or a given key dataset. Warning : The data of the ObjectArray will be flattened and it couldn't be undone without the dotted parameters set to true.

var doa = new ObjectArray({
  dat: {
    long: {
      path: 'fixture1',
      dream: 'fixture2'
    }
  }
});

// Flatten at root without path
doa.flatten();
console.log(doa.data); // Output {path: 'fixture1', dream: 'fixture2'}
// Flatten at root without path
doa.flatten(true);
console.log(doa.data); // Output {dat.long.path: 'fixture1', dat.long.dream: 'fixture2'}

Clone

The clone method returns a brand new clone of the current ObjectArray. If you have flattened dotted keys, you can provide falseas parameter to unflatten the data and restore the object hierarchy.

Iterations

forEach

The forEach method works exactly the same way than in the vanilla array object. The callback can take as much as three arguments quite self-explanatory. A forEach call can be done only on a dataset with a second parameter.

var doa = new ObjectArray({
  dat: {
    long: {
      path: 'fixture1',
      dream: 'fixture2'
    }
  }
});

doa.forEach(function(value, key, index) {
  console.log(key);
}); // will output dat

doa.forEach(function(value, key, index) {
  console.log(value);
}, 'dat.long'); // will output 'fixture1', 'fixture2'

reduce

The reduce method works exactly the same way than in the vanilla array object except that the key is provided to the callback function as a third parameter.

As forEach, reduce can be easily run on a subset instead at top-level with providing the key of the subset as second parameter. See API for details

Serializers

Embedded Serializers are provided for common cases. Each can be run on a dataset with providing the dotted key of the dataset as parameter.

stylesToString

stylesToString will convert the dataset to a string suitable to a style attribute. Keys will be converted from camel-case to dash-case if needed.

let doa = new ObjectArray({
  position: 'absolute',
  display: 'flex'
});

doa.styleString(): // returns 'position:absolute;display:flex'

urlEncode

urlEncode will convert the dataset to a string suitable to a query part of an URI

let doa = new ObjectArray({
  input: 'test',
  glob: '**/*',
  alias: 'test fixture'
});

doa.urlEncode(): // returns 'input=test&glob=**%2F*&alias=test%20fixture'

formUrlEncode

formUrlEncode will convert the dataset to a string suitable for sending as a form-url-encoded data

let doa = new ObjectArray({
  input: 'test',
  glob: '**/*',
  alias: 'test fixture'
});

doa.urlEncode(): // returns 'input=test&glob=**%2F*&alias=test+fixture'

Parsers

stringToStyles

stringToStyles will import a style-like string, split it into keys/values data and stores then into data. Keys will be converted from dash-case to camel-case if needed.

let doa = new ObjectArray();

doa.stringToStyles('position:absolute;display:flex');

console.log(doa.data): // outputs {position: 'absolute', display: 'flex'}

Helpers

camelize

camelize will convert a string to camel-case by removing spaces or dashes and uppercasing following letter.

dashize

camelize will convert a string to dash-case by replacing spaces with dashes and prepending dash to each capitalized first-letter and lowercase them/

JSON support

You can easily use ObjectArrays to manipulate JSON data. Just rely on JSON native object to import your JSON structure, manipulate it with ObjectArray ease and get it back at the end 😉

var jstring = '{"dat": {"long": {"path": "foo", "dream": "baz"}}}';
var doa = new ObjectArray(JSON.parse(jstring));

// Let's say we want to move all dat.long stuff to a short thing
doa.push('short', doa.dataset('dat.long')).remove('dat');
      
console.log(JSON.stringify(doa.data)); // outputs {"short":{"path":"foo","dream":"baz"}}

Bugs and features requests

ObjectArray is test-driven though it did not prevent all issues. Please report here any trouble or features request.

Want to help ?

There is many more to do to implements othe features. Don't mind fork DOA, tweak it and submit a pull request 😉