Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .github/workflows/verify-build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: Verify Build

on:
pull_request:
branches:
- main

jobs:
build:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: 20

- name: Install dependencies
run: npm install

- name: Run build
run: npm run build

- name: Run tests
run: npm test
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules
node_modules
dist
147 changes: 146 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,146 @@
# deep-key
# @nuc-lib/deep-key

## Description

`@nuc-lib/deep-key` is a utility library designed to simplify working with deeply nested objects in JavaScript. This is intended to be used when you work with dynamic keys or when you are not sure if the property exists. It provides a set of functions so you don't have to deal with the complexity of checking for the existence of properties at each level of the object.

## Features

- Safely access deeply nested properties.
- Filter arrays based on nested properties.
- Sort arrays based on nested properties.
- Lightweight and easy to integrate.

## Usage

### Accessing Nested Properties

The `getKeyValue` utility lets you access nested properties using a dot notation string. If the property does not exist, it returns `undefined` instead of throwing an error.

The key is a string that represents the path to the property you want to access. The path is defined using dot notation, where each level of the object is separated by a dot.

```javascript
import { getKeyValue } from '@nuc-lib/deep-key';

const guy = {
id: 2,
personalInfo: { name: 'John Doe', age: 12, city: 'New York' },
contacts: [
{ name: 'Jane Doe', email: 'afk@example.com' },
{ name: 'Alice Smith', email: 'alice@example.com' },
{ name: 'Bob Johnson', email: 'bob@example.com' },
{ name: 'Charlie Brown', email: 'charlie@example.com' }
],
associatedIds: [23, 43, 67, 89]
};

getKeyValue(guy, 'personalInfo.name'); // 'John Doe'
getKeyValue(guy, 'personalInfo.age'); // 12
getKeyValue(guy, 'personalInfo.city'); // 'New York'
getKeyValue(guy, 'personalInfo.active'); // undefined -> no error thrown
```

For arrays there are two ways to access the values:

- Getting an element in a specific index.

```javascript
getKeyValue(guy, 'contacts.0');
// { name: 'Jane Doe', email: 'afk@example.com' }
getKeyValue(guy, 'contacts.0.name'); // 'Jane Doe'
getKeyValue(guy, 'contacts.0.email'); // 'afk@example.com'
```

- Getting all the values in the array. A key wrapped in `[]` represents an actual mapping over the array, this means it will return an array of values from the parent array.

> **Note:** There is no need to use the `[]` notation if you are not using TypeScript. The utility will still map over the array and return the values. This is just a visual aid to show that the key is an array to be mapped.

```javascript
getKeyValue(guy, '[contacts].name');
// ['Jane Doe', 'Alice Smith', 'Bob Johnson', 'Charlie Brown']
getKeyValue(guy, 'contacts.name');
// ['Jane Doe', 'Alice Smith', 'Bob Johnson', 'Charlie Brown'] -> Works the same as above
getKeyValue(guy, '[contacts].invalidKey');
// [undefined, undefined, undefined, undefined] -> no error thrown
```

### Filtering By Nested Properties

The `filterByKeyValue` utility allows you to filter an array of objects based on a nested property. It returns a new array containing only the objects that match the specified key and value.

```javascript
import { filterByKeyValue } from '@nuc-lib/deep-key';

const people = [
{
id: 1,
name: 'John Doe',
age: 25,
parentIds: [1, 2],
address: { city: 'Houston', zip: '10001' }
},
{
id: 2,
name: 'Jane Doe',
age: 30,
parentIds: [3, 4],
address: { city: 'Los Angeles', zip: '90001' }
},
{
id: 3,
name: 'Alice Smith',
age: 22,
parentIds: [5, 6],
address: { city: 'Chicago', zip: '60601' }
},
{
id: 4,
name: 'Bob Johnson',
age: 28,
parentIds: [7, 8],
address: { city: 'Houston', zip: '77001' }
}
];

filterByKeyValue(people, 'age', 25);
// [ { id: 1, name: 'John Doe', age: 25, parentIds: [ 1, 2 ], address: { city: 'Houston', zip: '10001' } } ]

filterByKeyValue(people, 'address.city', 'Houston');
// [
// { id: 1, name: 'John Doe', age: 25, parentIds: [ 1, 2 ], address: { city: 'Houston', zip: '10001' } },
// { id: 4, name: 'Bob Johnson', age: 28, parentIds: [7, 8], address: { city: 'Houston', zip: '77001' } }
// ]
filterByKeyValue(people, 'address', 'Houston');
// [] -> no error thrown
```

Strict mode for filter arrays is also supported. This means that the filter will only return the objects that match the exact value of the key.

```javascript
filterByKeyValue(people, 'age', [22, 25]);
// [
// { id: 1, name: 'John Doe', age: 25, parentIds: [ 1, 2 ], address: { city: 'Houston', zip: '10001' } },
// { id: 3, name: 'Alice Smith', age: 22, parentIds: [5, 6], address: { city: 'Chicago', zip: '60601' } },
// ]
```

You can do a **loose filter** by passing `false` as the fourth argument.
This means that the filter will return the objects that match any of the values in the array.

```javascript
filterByKeyValue(people, 'age', [22, 25], false);
// [
// { id: 1, name: 'John Doe', age: 25, parentIds: [ 1, 2 ], address: { city: 'Houston', zip: '10001' } },
// { id: 3, name: 'Alice Smith', age: 22, parentIds: [5, 6], address: { city: 'Chicago', zip: '60601' } },
// ]
```

Use a custom filter function by passing a function as the third argument.

```javascript
filterByKeyValue(people, 'age', (value) => value > 25);
// [
// { id: 2, name: 'Jane Doe', age: 30, parentIds: [3, 4], address: { city: 'Los Angeles', zip: '90001' } },
// { id: 4, name: 'Bob Johnson', age: 28, parentIds: [7, 8], address: { city: 'Houston', zip: '77001' } }
// ]
```
49 changes: 40 additions & 9 deletions lib/utils/filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,60 @@ import { getKeyValue } from './value';

import type { DeepKeyOf, TObject } from '../types';

type FilterValue = string | number | boolean | string[] | number[];

/**
* This function filters an array of objects based on a specific key and value.
* It returns a new array containing only the objects that match the given key-value pair.
* @param list The array of objects to filter.
* @param key The key to filter by.
* @param value The value to match against the specified key.
* @param filter The value to filter by. This can be a single value or an array of values.
* It also supports a function that takes the value of the key and returns a boolean.
* @param mode The mode of filtering. 'strict' checks for exact matches, while 'loose' allows for partial matches.
* Only applies to array filter values.
* This is ignored if custom filter function is provided.
* @returns A new array of objects that match the specified key-value pair.
*/
export const filterArrayByKeyValue = <T extends TObject>(
export const filterByKeyValue = <T extends TObject>(
list: T[],
key: DeepKeyOf<T>,
value: string | number | boolean | string[] | number[]
filter: ((value: FilterValue) => boolean) | FilterValue,
strict = true
) => {
return list.filter((item) => {
if (Array.isArray(value)) {
if (value.length === 0) {
const itemKeyValue = getKeyValue(item, key);
// Early return if itemKeyValue is undefined or an object
if (!itemKeyValue) {
return false;
}
// Verify if filter is a function and call it with itemKeyValue
if (typeof filter === 'function') {
try {
return filter(itemKeyValue);
} catch {
return false;
}
return value.some((val) => val === getKeyValue(item, key));
}
if (value) {
return true;
// If filter is an array, check if itemKeyValue is in the array
if (Array.isArray(filter)) {
if (filter.length === 0) {
return false;
}

if (Array.isArray(itemKeyValue)) {
if (strict) {
return filter.every((val) => itemKeyValue.includes(val));
}
return filter.some((val) => itemKeyValue.includes(val));
}

return filter.some((val) => val === itemKeyValue);
}
return getKeyValue(item, key) === value;
// If key value is an array check if filter is in the array
if (Array.isArray(itemKeyValue)) {
return itemKeyValue.some((val) => val === filter);
}

return itemKeyValue === filter;
});
};
2 changes: 1 addition & 1 deletion lib/utils/sort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { DeepKeyOf, TObject } from '../types';
* @param order the order to sort by. Available values are 'ASC' and 'DESC'.
* @returns an array sorted by the given key and order.
*/
export const sortByProp = <T extends TObject>(
export const sortByKeyValue = <T extends TObject>(
array: T[],
key: DeepKeyOf<T>,
order: 'ASC' | 'DESC' = 'ASC'
Expand Down
Loading