npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@trojs/objects

v9.0.1

Published

Create valid JavaScript objects

Downloads

2,538

Readme

Create valid JavaScript objects

NPM version Coverage Quality Gate Status Bugs Code Smells Technical Debt Vulnerabilities Maintainability Rating Reliability Rating Security Rating

Create objects and validate the values, so you know all values are ok. You don't have to create code to validate all fields of an object, just write a schema. Also get more usefull methods to work with objects.

Installation

npm install @trojs/objects or yarn add @trojs/objects

Test the package

npm run test or yarn test

Validation

For validate the objects, it use the package @trojs/validation (https://www.npmjs.com/package/@trojs/validator) It will throw an error if the object isnt valid. For all posibilities, check the validation package readme.

Usage

Example usage:

import { Obj } from '@trojs/objects'

const addressSchema = {
    street: String,
    number: Number,
    postalCode: String,
    city: String,
    country: String,
};

const Address = Obj({ schema: addressSchema })

const myAddress = Address.create({
    street: 'Abc',
    number: 42,
    postalCode: '1234AB',
    city: 'Example',
    country: 'The Netherlands'
})

console.log(myAddress)

{
    street: 'Abc',
    number: 42,
    postalCode: '1234AB',
    city: 'Example',
    country: 'The Netherlands'
}

You can also define sub schemas:

import { Obj } from '@trojs/objects'

const filterSchema = {
  key: String,
  type: String
}

const optionSchema = {
  value: String,
  'count?': Number
}

const selectFilterSchema = {
  ...filterSchema,
  options: optionSchema
}

const SelectFilter = Obj({ schema: selectFilterSchema })

const multiselect = SelectFilter.create({
    key: 'status',
    type: 'multiselect',
    options: [
        {
            value: 'open',
            count: 42
        },
        {
            value: 'closed'
        }
    ]
})

console.log(multiselect)

{
    street: 'status',
    number: 'multiselect',
    options: [
        {
            value: 'open',
            count: 42
        },
        {
            value: 'closed'
        }
    ]
}

Catching validation errors:

try {
    const multiselect = SelectFilter.create({
        key: 'status',
        options: [
            {
                value: 'open',
                count: 42
            },
            {
                value: 'closed'
            }
        ]
    })
} catch (error) {
    console.log(error.message)
}

'The field type should be a String'

You can also map the values:

const testSchema = {
    a: Number,
    b: Number,
};

const Test = Obj({ schema: testSchema });

const input = {
    a: 1,
    b: 2,
};

const test = Test.create(input)

const mappedResults = test.map((x) => x * 2)

// Or you can do:
const double = (x) => x * 2
const mappedResults2 = test.map(double)

console.log(mappedResults)

{
    a: 2,
    b: 4,
};

You can also filter the values:

const testSchema = {
    a: Number,
    b: Number,
};

const Test = Obj({ schema: testSchema });

const input = {
    a: 1,
    b: 2,
};

const test = Test.create(input)

const filteredResults = test.filter((x) => x === 1)

// Or you can do:
const onlyOne = (x) => x === 1
const filteredResults2 = test.filter(onlyOne)

console.log(filteredResults)

{
    a: 1,
};

You can also use every:

const testSchema = {
    a: Number,
    b: Number,
};

const Test = Obj({ schema: testSchema });

const input = {
    a: 1,
    b: 2,
};

const test = Test.create(input)

const everythingIsBelowThree = test.every((x) => x < 3)

// Or you can do:
const isBelowThree = (x) => x < 3
const everythingIsBelowThree2 = test.every(isBelowThree)

console.log(everythingIsBelowThree)

true

You can also use some:

const testSchema = {
    a: Number,
    b: Number,
};

const Test = Obj({ schema: testSchema });

const input = {
    a: 1,
    b: 2,
};

const test = Test.create(input)

const someAreTwo = test.some((x) => x === 2)

// Or you can do:
const isTwo = (x) => x === 2
const someAreTwo2 = test.some(isTwo)

console.log(someAreTwo)

true

If you have some data, and you have to transform the data to the schema, you can use the parse method.

const subSchema = {
    a: Number,
    b: Boolean,
    'c?': String,
};

const testSchema = {
    a: Number,
    b: Boolean,
    'c?': String,
    subSchema,
};

const Test = Obj({ schema: testSchema });


const input = {
    a: '42',
    b: 'true',
    c: 42,
    subSchema: {
        a: '42',
        b: 'true',
        c: 42,
    },
};

Test.parse(input)

{
    a: 42,
    b: true,
    c: '42',
    subSchema: {
        a: 42,
        b: true,
        c: '42',
    },
};

Example usage without a schema: ...

const flatter = Obj().create({
    a: 1,
    b: 2,
    c: [3, 4],
    d: { e: 5, f: 6 },
    g: { h: { i: 7 } }
})

You can get the flat object by:

flatter.flat

{
    a: 1,
    b: 2,
    "c.0": 3,
    "c.1": 4,
    "d.e": 5,
    "d.f": 6,
    "g.h.i": 7
}

You can get the object entries by:

flatter.entries()

[
    ["a", 1],
    ["b", 2],
    ["c.0", 3],
    ["c.1", 4],
    ["d.e", 5],
    ["d.f", 6],
    ["g.h.i", 7]
]

You can get the object keys by:

flatter.keys()

["a", "b", "c.0", "c.1", "d.e", "d.f", "g.h.i"]

You can get the object values by:

flatter.values()

[1, 2, 3, 4, 5, 6, 7]

You can get the object length by:

flatter.length

7

You can get by key by:

flatter.getByKey("g.h.i")

7

Or set a fallback value by:

flatter.getByKey("x.y.z", 42)

42
flatter.getByKey("d")

{ e: 5, f: 6 }

Check if the object has a key:

flatter.has("g.h.i")

true

Check if the object has key includes a value:

flatter.includes("g.h")

true

You can get only some fields from the object:

flatter.getKeys(['a', 'c', 'd.e', 'g.h'])

{
    a: 1,
    c: [3, 4],
    'd.e': 5,
    'g.h': { i: 7 },
}

And you can also get some fields from the object in the flat format:

flatter.getFlatKeys(['a', 'c', 'd.e', 'g.h'])

{
    a: 1,
    'c.0': 3,
    'c.1': 4,
    'd.e': 5,
    'g.h.i': 7,
}

And you can also use the map method:


flatter.flatMap((x) => x * 2)

{
    a: 2,
    b: 4,
    'c.0': 6,
    'c.1': 8,
    'd.e': 10,
    'd.f': 12,
    'g.h.i': 14,
};

And you can also use the flatFilter method:

const flatter = Obj().create({
    a: 1,
    b: 2,
    c: [1, 2],
    d: { e: 1, f: 2 },
    g: { h: { i: 1 } }
})

flatter.flatFilter((x) => x === 1)

{
    a: 1,
    'c.0': 1,
    'd.e': 1,
    'g.h.i': 1,
};

And you can also use the flatEvery method:

const flatter = Obj().create({
    a: 1,
    b: 2,
    c: [1, 2],
    d: { e: 1, f: 2 },
    g: { h: { i: 1 } }
})

flatter.flatEvery((x) => x < 3)

true

And you can also use the flatSome method:

const flatter = Obj().create({
    a: 1,
    b: 2,
    c: [1, 2],
    d: { e: 1, f: 2 },
    g: { h: { i: 1 } }
})

flatter.flatSome((x) => x === 2)

true

For arrays you can also use createAll and parseAll. It works the same as create and parse but it can do it on every item in an array.