dot-wild
Use powerful dot notation (dot path + wildcard) to manipulate properties of JSON.
Table of Contents
Install
$ npm install dot-wild
Usage
Basic
const dot = require("dot-wild");
dot.get({ foo: { bar: "baz" } }, "foo.bar");
dot.get({ "foo.bar": "baz" }, "foo\\.bar");
dot.get({ "foo.bar": "baz" }, "notfound", "default");
const authorData = {
authors: [
{ username: "tsuyoshiwada", profile: { age: 24 } },
{ username: "sampleuser", profile: { age: 30 } },
{ username: "foobarbaz", profile: { age: 33 } }
]
};
dot.get(authorData, "authors.*.username");
dot.get(authorData, "authors.*.profile.age");
dot.set({ foo: { bar: "baz" } }, "foo.bar", "newvalue");
dot.set([{ foo: {} }], "0.foo.bar.baz", "value");
const members = [
{ username: "tsuyoshiwada", profile: { age: 24 } },
{ username: "sampleuser", profile: { age: 30 } },
{ username: "foobarbaz", profile: { age: 33 } }
];
dot.set(members, "*.id", 1);
dot.delete({ foo: { bar: "baz" } }, "foo.bar");
dot.delete(members, "*.profile");
dot.has({ foo: { bar: "baz" } }, "foo.bar");
dot.has(members, "*.profile.age");
dot.has({ foo: { bar: "baz" } }, "foo\\.bar");
dot.has(members, "*.notfound.key");
Advanced
const dot = require("dot-wild");
const postData = {
text: "ok",
code: 200,
data: {
posts: [
{ id: 1, title: "post 1" },
{ id: 2, title: "post 2" }
],
tags: [
{ id: 1, name: "tag 1" },
{ id: 2, name: "tag 2" }
]
}
};
dot.flatten(data);
dot.expand({ "foo.bar": "baz" });
API
All methods return a new object or array. (immutable)
get(data, path, [value]): Object | Array
set(data, path, value): Object | Array
delete(data, path): Object | Array
has(data, path): boolean
flatten(data): Object
expand(data): Object | Array
data
type: Object | Array
Original object or array. Destructive operation is not performed.
path
type: string
Path of the property in JSON object. Use the .
to select properties.
Separator in path syntax can be escaped by using the \\.
.
And, you can match arrays by using *
(wildcard).
value
type: any
Value to set at path or optional default value to return from get.
Contribute
- Fork it!
- Create your feature branch: git checkout -b my-new-feature
- Commit your changes: git commit -am 'Add some feature'
- Push to the branch: git push origin my-new-feature
- Submit a pull request :D
License
MIT © tsuyoshiwada