Introduction to is-plain-obj
is-plain-obj is a lightweight JavaScript utility designed to check if a value is a plain object. Plain objects are objects created using the {}
syntax, new Object()
, or Object.create(null)
. This library helps developers identify plain objects and ensures robust and error-free code execution.
API Examples
Below are several examples of how to use is-plain-obj
in your JavaScript projects:
Basic Usage
const isPlainObj = require('is-plain-obj');
console.log(isPlainObj({})); // => true
console.log(isPlainObj(Object.create(null))); // => true
console.log(isPlainObj([])); // => false
console.log(isPlainObj(new Date())); // => false
Example in a Function
function handleData(input) {
if (isPlainObj(input)) {
console.log("Received a plain object!");
} else {
console.log("Received something else.");
}
}
handleData({ key: "value" }); // => "Received a plain object!"
handleData(new Date()); // => "Received something else."
Check Nested Objects
const nestedObj = {
level1: {
level2: {
key: "value"
}
}
};
function checkNested(obj) {
for (const key in obj) {
if (isPlainObj(obj[key])) {
console.log(`${key} is a plain object`);
} else {
console.log(`${key} is something else`);
}
}
}
checkNested(nestedObj.level1); // => "level2 is a plain object"
Handling API Responses
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
if (isPlainObj(data)) {
console.log("Received plain object from API");
} else {
console.log("API response is not a plain object");
}
});
App Example
Here is an example of a simple Node.js application utilizing is-plain-obj
to handle different data types, such as ensuring that configuration objects are plain objects:
const isPlainObj = require('is-plain-obj');
// Define configuration settings
const config = {
database: {
host: 'localhost',
port: 5432
},
apiKeys: {}
};
// Function to update configuration
function updateConfig(newConfig) {
if (!isPlainObj(newConfig)) {
throw new Error('Configuration must be a plain object');
}
Object.assign(config, newConfig);
}
try {
updateConfig({ apiKeys: { key1: 'value1' } });
console.log('Configuration updated successfully');
} catch (error) {
console.error(error.message);
}
console.log(config);
// Expected output:
// Configuration updated successfully
// { database: { host: 'localhost', port: 5432 }, apiKeys: { key1: 'value1' } }
Using is-plain-obj
ensures that only plain objects can be used for configuration updates, helping maintain data integrity in your application.
Hash: f88c4b85ffb9f77751c50775ee6e2a66a336a656712d23fa7870f345d61137f8