Json Function
Search…
Schema
The "Schema" function is a great way to reconfigure your json data and make it your own.
Github repository for your stars.

Usage

Install

1
$ npm install json-function
Copied!

Import

1
import { schema } from 'json-function';
Copied!

Usage

Example Data
1
const data = [
2
{
3
id: 0,
4
user: {
5
firstname: "John",
6
lastname: "Doe"
7
},
8
title: "Book Name"
9
},
10
{
11
id: 1,
12
user: {
13
firstname: "Johnny",
14
lastname: "Doe"
15
},
16
title: "Book Name 2"
17
}
18
];
Copied!
Syntax
1
schema(data, {
2
book: {
3
id: "id",
4
title: "title"
5
},
6
firstname: "user.firstname",
7
lastname: "user.lastname"
8
});
Copied!
Output
1
[
2
{
3
firstname: "John",
4
lastname: "Doe",
5
book: {
6
id: 0,
7
title: "Book Name"
8
}
9
},
10
{
11
firstname: "Johnny",
12
lastname: "Doe",
13
book: {
14
id: 1,
15
title: "Book Name 2"
16
}
17
}
18
];
Copied!
Apart from this wonderful method, there are also some advanced uses.
Schema has a calback that hosts useful tools.
Example Data
1
const data = [
2
{
3
id: 0,
4
user: {
5
firstname: "John",
6
lastname: "Doe"
7
},
8
title: "Book Name"
9
},
10
{
11
id: 1,
12
user: {
13
firstname: "Johnny",
14
lastname: "Doe"
15
},
16
title: "Book Name 2"
17
}
18
];
Copied!
Syntax
join()
The default separator is a space.
1
schema(data, (sc) => ({
2
id: 'id',
3
fullName: sc.join('user.firstname', 'user.lastname')
4
}));
Copied!
Output
1
[
2
{
3
id: 0,
4
fullName: "John Doe"
5
},
6
{
7
id: 1,
8
fullName: "Johnny Doe"
9
}
10
];
Copied!
To use a custom separator.
1
schema(data, (sc) => ({
2
id: 'id',
3
fullName: sc.join('user.firstname', 'user.lastname', { separator: '_' })
4
}));
Copied!
Output
1
[
2
{
3
id: 0,
4
fullName: "John_Doe"
5
},
6
{
7
id: 1,
8
fullName: "Johnny_Doe"
9
}
10
];
Copied!
custom()
Example Data
1
const data = [
2
{
3
id: 0,
4
createdAt: "2019-03-07T19:22:36+00:00",
5
user: {
6
firstname: "Aykut",
7
lastname: "Kardaş"
8
}
9
},
10
{
11
id: 1,
12
createdAt: "2019-03-02T19:22:36+00:00",
13
user: {
14
firstname: "John",
15
lastname: "Doe"
16
}
17
}
18
];
Copied!
Usage
1
schema(data, sc => ({
2
id: "id",
3
fullName: sc.custom(
4
(firstname, lastname) => `${firstname.toUpperCase()} ${lastname.toUpperCase()}`,
5
"user.firstname",
6
"user.lastname"
7
),
8
createdAt: sc.custom(
9
createdAt => moment(createdAt).format("MM/DD/YYYY"),
10
"createdAt"
11
),
12
idIncrement: sc.custom(id => id + 1, "id")
13
}));
Copied!
Output
1
[
2
{
3
id: 0,
4
fullName: "AYKUT KARDAŞ",
5
createdAt: "03/07/2019",
6
idIncrement: 1
7
},
8
{
9
id: 1,
10
fullName: "JOHN DOE",
11
createdAt: "03/02/2019",
12
idIncrement: 2
13
}
14
]
Copied!
Last modified 2yr ago
Copy link
Contents
Usage