Dark Mode

Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Like loadash.get, but in ~200 bytes

License

Notifications You must be signed in to change notification settings

micheleriva/mjn

Repository files navigation

Simple utility to check if a key or a value exists in an object.



Sponsors



No cannot get property x of undefined. Just returns void 0 (undefined) if a value or a key does not exist. Highly inspired from Java's Optional Type.

Index

  • Installation
  • Usage
    • Simple Example
    • Real World React Example
  • Demos
  • License

Installation

yarn

yarn add mjn

npm

npm install --save mjn

cdn

<script src="https://cdn.jsdelivr.net/npm/mjn@latest/dist/dist.min.js">script>

Usage

Simple Example

"no value!" console.log(e); // => "I can be a function!"">import maybe from "mjn"; // Or import the library as you wish using npm or CDN script tag!

const myObject = {
user: {
name: "John",
surname: "Doe",
birthday: "1995-01-29",
contacts: {
email: "foo@bar.com",
phone: "000 0000000"
},
languages: ["english", "italian"]
}
};

const a = maybe(myObject, "user.name");
const b = maybe(myObject, "user.languages[1]");
const c = maybe(myObject, "foo.bar.baz");
const d = maybe(myObject, "foo.bar.baz", "no value!");
const e = maybe(myObject, "foo.bar.baz", () => "I can be a function!");


console.log(a); // => John
console.log(b); // => italian
console.log(c); // => won't log anything!
console.log(d); // => "no value!"
console.log(e); // => "I can be a function!"

Real World React Example

); const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);">import React from "react";
import ReactDOM from "react-dom";
import maybe from "mjn";

const user = {
name: {
first_name: "John",
last_name: "Doe"
},
contacts: {
phone: "+00 000 0000000",
email: "john@doe.do"
}
};

const App = () => (
<div className="App">
<h1>Hello {maybe(user, "name.first_name")}!h1>
<h2> {maybe(user, "contacts.email")} h2>

<p>
{maybe(user, "contacts.phone.office", "You don't have an office phone.")}
p>
div>
);

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Demos

React.js

Vue.js

Vanilla JS

Contributors

Thanks goes to these wonderful people (emoji key):


Michele Riva


Paolo Roth


Mattia Astorino

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT

About

Like loadash.get, but in ~200 bytes

Topics

Resources

Readme

License

MIT license

Stars

Watchers

Forks

Sponsor this project

Packages

No packages published

Contributors 3