Json Function
Search…
Where
The "Where" function provides a comfortable method for filtering a json data.
Github repository for your stars.

Usage

Install

1
$ npm install json-function
Copied!

Import

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

Usage

Example Data
1
const data = [
2
{
3
id: 1,
4
userId: 1,
5
title: "delectus aut autem",
6
completed: false,
7
education: {
8
isDone: true
9
}
10
},
11
{
12
id: 2,
13
userId: 1,
14
title: "lorem ipsum",
15
completed: true,
16
education: {
17
isDone: true
18
}
19
},
20
{
21
id: 3,
22
userId: 2,
23
title: "quis ut nam facilis et officia qui",
24
completed: false,
25
education: {
26
isDone: false
27
}
28
}
29
];
Copied!

Basic Syntax

1
where(data, { userId: 1 });
Copied!
Output
1
[
2
{
3
id: 1,
4
userId: 1,
5
title: "delectus aut autem",
6
completed: false,
7
education: {
8
isDone: true
9
}
10
},
11
{
12
id: 2,
13
userId: 1,
14
title: "lorem ipsum",
15
completed: true,
16
education: {
17
isDone: true
18
}
19
}
20
];
Copied!

AND Syntax

1
where(data, { userId: 1, completed: true });
Copied!
Output
1
[
2
{
3
id: 2,
4
userId: 1,
5
title: "lorem ipsum",
6
completed: true,
7
education: {
8
isDone: true
9
}
10
}
11
];
Copied!

OR Syntax

1
where(data, [{ userId: 1, completed: true }, { userId: 2, completed: false }]);
Copied!
Output
1
[
2
{
3
id: 2,
4
userId: 1,
5
title: "lorem ipsum",
6
completed: true,
7
education: {
8
isDone: true
9
}
10
},
11
{
12
id: 3,
13
userId: 2,
14
title: "quis ut nam facilis et officia qui",
15
completed: false,
16
education: {
17
isDone: false
18
}
19
}
20
];
Copied!
Use "callback" for advanced filter.
1
// id <= 3
2
where(data, (wh) => ({
3
id: wh.lte(3),
4
}));
Copied!
Other wh methods.
1
wh.lte(3) // value <= 3
2
wh.lt(3) // value < 3
3
wh.gte(3) // value >= 3
4
wh.gt(3) // value > 3
5
wh.between(3,5) // value >= 3 && value <= 5
6
wh.eq("3") // value == 3
7
wh.ne("3") // value != 3
8
wh.in('test') // value.includes('test')
9
wh.nin('test') // !value.includes('test')
10
wh.oneOf([1, 2, 3]) // [1, 2, 3].includes(value)
Copied!

Deep Where Syntax

1
where(data, { 'education.isDone': true }, { deep: true });
Copied!
It is necessary to add a new option argument to use "Deep Where".
{ deep: true }
Output
1
[
2
{
3
id: 1,
4
userId: 1,
5
title: "delectus aut autem",
6
completed: false,
7
education: {
8
isDone: true
9
}
10
},
11
{
12
id: 2,
13
userId: 1,
14
title: "lorem ipsum",
15
completed: true,
16
education: {
17
isDone: true
18
}
19
},
20
];
Copied!
Last modified 1yr ago