Where

The "Where" function provides a comfortable method for filtering a json data.

Github repository for your stars.

Usage

Install

$ npm install json-function

Import

import { where } from 'json-function';

Usage

Example Data

const data = [
{
id: 1,
userId: 1,
title: "delectus aut autem",
completed: false,
education: {
isDone: true
}
},
{
id: 2,
userId: 1,
title: "lorem ipsum",
completed: true,
education: {
isDone: true
}
},
{
id: 3,
userId: 2,
title: "quis ut nam facilis et officia qui",
completed: false,
education: {
isDone: false
}
}
];

Basic Syntax

where(data, { userId: 1 });

Output

[
{
id: 1,
userId: 1,
title: "delectus aut autem",
completed: false,
education: {
isDone: true
}
},
{
id: 2,
userId: 1,
title: "lorem ipsum",
completed: true,
education: {
isDone: true
}
}
];

AND Syntax

where(data, { userId: 1, completed: true });

Output

[
{
id: 2,
userId: 1,
title: "lorem ipsum",
completed: true,
education: {
isDone: true
}
}
];

OR Syntax

where(data, [{ userId: 1, completed: true }, { userId: 2, completed: false }]);

Output

[
{
id: 2,
userId: 1,
title: "lorem ipsum",
completed: true,
education: {
isDone: true
}
},
{
id: 3,
userId: 2,
title: "quis ut nam facilis et officia qui",
completed: false,
education: {
isDone: false
}
}
];

Use "callback" for advanced filter.

// id <= 3
where(data, (wh) => ({
id: wh.lte(3),
}));

Other wh methods.

wh.lte(3) // value <= 3
wh.lt(3) // value < 3
wh.gte(3) // value >= 3
wh.gt(3) // value > 3
wh.between(3,5) // value >= 3 && value <= 5
wh.eq("3") // value == 3
wh.ne("3") // value != 3
wh.in('test') // value.includes('test')
wh.nin('test') // !value.includes('test')
wh.oneOf([1, 2, 3]) // [1, 2, 3].includes(value)

Deep Where Syntax

where(data, { 'education.isDone': true }, { deep: true });

It is necessary to add a new option argument to use "Deep Where".

{ deep: true }

Output

[
{
id: 1,
userId: 1,
title: "delectus aut autem",
completed: false,
education: {
isDone: true
}
},
{
id: 2,
userId: 1,
title: "lorem ipsum",
completed: true,
education: {
isDone: true
}
},
];