Node.js Object Ninja Moves 🥷
Accessing Object Properties
// Define a sample object
const person = {
name: 'John Doe',
age: 25,
job: 'Developer'
};
// Accessing object properties
console.log('Name:', person.name);
console.log('Age:', person.age);
console.log('Job:', person.job);
Accessing and printing values of properties in a JavaScript object.
Iterating Through Object Keys
// Define a sample object
const car = {
make: 'Toyota',
model: 'Camry',
year: 2022
};
// Iterating through object keys
for (const key in car) {
console.log(`${key}: ${car[key]}`);
}
Looping through the keys of a JavaScript object and printing their values.
Checking if a Key Exists in an Object
// Define a sample object
const fruitBasket = {
apple: 5,
banana: 3,
orange: 2
};
// Check if 'banana' key exists
if ('banana' in fruitBasket) {
console.log('Bananas found:', fruitBasket.banana);
} else {
console.log('Bananas not found.');
}
Checking if a specific key exists in a JavaScript object.
Modifying Object Properties
// Define a sample object
const book = {
title: 'The Hitchhiker\'s Guide to the Galaxy',
author: 'Douglas Adams',
year: 1979
};
// Update the year property
book.year = 1980;
// Display the modified object
console.log('Updated Book:', book);
Modifying values of properties in a JavaScript object.
Working with Nested Objects
// Define a sample object with nesting
const addressBook = {
person1: {
name: 'Alice',
age: 30,
address: {
city: 'Wonderland',
country: 'Fairyland'
}
},
person2: {
name: 'Bob',
age: 28,
address: {
city: 'TechCity',
country: 'Geekland'
}
}
};
// Accessing nested properties
console.log('Alice\'s City:', addressBook.person1.address.city);
console.log('Bob\'s Country:', addressBook.person2.address.country);
Accessing properties in nested JavaScript objects.
Filtering Objects by Property Value
// Sample array of objects
const employees = [
{ name: 'Alice', department: 'HR', salary: 50000 },
{ name: 'Bob', department: 'IT', salary: 60000 },
{ name: 'Charlie', department: 'IT', salary: 75000 }
];
// Define a filter criteria (e.g., find IT department employees)
const departmentToFilter = 'IT';
// Use filter() to find matching objects
const itEmployees = employees.filter(employee => employee.department === departmentToFilter);
// Display the filtered objects
console.log(`Employees in ${departmentToFilter} department:`, itEmployees);
Find objects in an array that meet specific criteria based on property values.
Advanced Object Transformation
// Sample array of objects
const products = [
{ id: 1, name: 'Laptop', price: 1200 },
{ id: 2, name: 'Smartphone', price: 800 },
{ id: 3, name: 'Tablet', price: 500 }
];
// Use map() to create a new array with modified objects
const discountedProducts = products.map(product => ({
...product,
discountedPrice: product.price * 0.9
}));
// Display the transformed objects
console.log('Discounted Products:', discountedProducts);
Transform objects in an array into a new format using map().
Deep Object Search
// Sample nested object
const company = {
name: 'TechCo',
departments: {
hr: {
manager: 'Alice',
employees: ['Bob', 'Charlie']
},
it: {
manager: 'Dave',
employees: ['Eve', 'Frank']
}
}
};
// Function to search for an employee name
function findEmployee(employeeName) {
for (const department in company.departments) {
const employees = company.departments[department].employees;
if (employees.includes(employeeName)) {
return `${employeeName} found in ${department} department.`;
}
}
return `${employeeName} not found.`;
}
// Example usage
console.log(findEmployee('Charlie'));
Perform a deep search in nested objects to find a specific value.
Removing Objects by Condition
// Sample array of objects
let tasks = [
{ id: 1, title: 'Task 1', completed: true },
{ id: 2, title: 'Task 2', completed: false },
{ id: 3, title: 'Task 3', completed: true }
];
// Remove completed tasks
tasks = tasks.filter(task => !task.completed);
// Display the updated array
console.log('Active Tasks:', tasks);
Remove objects from an array that meet a specified condition.
Object Aggregation with Reduce
// Sample array of objects
const expenses = [
{ category: 'Food', amount: 50 },
{ category: 'Transportation', amount: 30 },
{ category: 'Entertainment', amount: 20 }
];
// Use reduce() to calculate the total expense
const totalExpense = expenses.reduce((accumulator, expense) => accumulator + expense.amount, 0);
// Display the total expense
console.log('Total Expense:', totalExpense);
Aggregate values from multiple objects into a single result using reduce().
Dynamically Creating Objects
// Sample data from an external source
const dataFromAPI = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
};
// Dynamically create an object from the external data
const dynamicObject = {};
for (const key in dataFromAPI) {
dynamicObject[key] = dataFromAPI[key];
}
// Display the dynamically created object
console.log('Dynamic Object:', dynamicObject);
Demonstrate dynamic creation of objects based on external data.
Merging Objects
// Sample objects to merge
const object1 = { a: 1, b: 2 };
const object2 = { b: 3, c: 4 };
// Use the spread operator to merge objects
const mergedObject = { ...object1, ...object2 };
// Display the merged object
console.log('Merged Object:', mergedObject);
Merge properties from multiple objects into a single object.
Immutable Object Update
// Sample object
const originalObject = { name: 'John', age: 30 };
// Update the age property while maintaining immutability
const updatedObject = { ...originalObject, age: 31 };
// Display the original and updated objects
console.log('Original Object:', originalObject);
console.log('Updated Object:', updatedObject);
Create a new object with updated properties while keeping the original object unchanged.
Advanced Object Filtering
// Sample array of objects
const inventory = [
{ name: 'Laptop', category: 'Electronics', price: 1200 },
{ name: 'Book', category: 'Stationery', price: 20 },
{ name: 'Headphones', category: 'Electronics', price: 150 }
];
// Advanced filtering: Find Electronics items under $200
const filteredItems = inventory.filter(item => item.category === 'Electronics' && item.price < 200);
// Display the filtered items
console.log('Filtered Items:', filteredItems);
Filter objects based on a complex condition using Array's filter() method.
Object Destructuring
// Sample object
const user = { id: 1, username: 'jsmith', email: 'jsmith@example.com' };
// Destructuring to extract specific properties
const { id, email } = user;
// Display the extracted properties
console.log('User ID:', id);
console.log('User Email:', email);
Extract specific properties from an object using destructuring.
Asynchronous Object Transformation
// Sample array of objects
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
// Simulate an asynchronous operation (e.g., fetching additional data)
function fetchAdditionalData(user) {
return new Promise(resolve => {
// Simulated delay
setTimeout(() => {
// Adding additional data
user.country = 'Unknown';
resolve(user);
}, 1000);
});
}
// Use Promise.all() to transform all objects asynchronously
const transformedUsers = Promise.all(users.map(user => fetchAdditionalData(user)));
// Display the transformed objects
transformedUsers.then(result => console.log('Transformed Users:', result));
Transform objects asynchronously using Promises.
Chaining Asynchronous Object Operations
// Sample object
const person = {
name: 'John Doe',
age: 25
};
// Simulate asynchronous operations (e.g., fetching and updating data)
function fetchData(data) {
return new Promise(resolve => {
setTimeout(() => {
// Simulated data fetching
data.location = 'Unknown';
resolve(data);
}, 1000);
});
}
function updateData(data) {
return new Promise(resolve => {
setTimeout(() => {
// Simulated data updating
data.age = 26;
resolve(data);
}, 800);
});
}
// Chain asynchronous operations using Promise chaining
fetchData(person)
.then(updatedData => updateData(updatedData))
.then(finalData => console.log('Final Data:', finalData));
Chain multiple asynchronous operations on objects using Promises.
Asynchronous Object Filtering
// Sample array of objects
const products = [
{ id: 1, name: 'Laptop', price: 1200 },
{ id: 2, name: 'Smartphone', price: 800 },
{ id: 3, name: 'Tablet', price: 500 }
];
// Asynchronously filter products based on a condition
function filterProductsAsync(products, condition) {
return new Promise(resolve => {
setTimeout(() => {
const filteredProducts = products.filter(product => condition(product));
resolve(filteredProducts);
}, 1000);
});
}
// Example usage: Filter products with a price below 1000 asynchronously
filterProductsAsync(products, product => product.price < 1000)
.then(result => console.log('Filtered Products:', result));
Filter objects asynchronously based on a condition using Promises.
Parallel Asynchronous Object Processing
// Sample array of objects
const tasks = [
{ id: 1, title: 'Task 1' },
{ id: 2, title: 'Task 2' },
{ id: 3, title: 'Task 3' }
];
// Simulate an asynchronous operation (e.g., processing tasks)
function processTask(task) {
return new Promise(resolve => {
setTimeout(() => {
// Simulated task processing
task.completed = true;
resolve(task);
}, Math.random() * 2000); // Random delay
});
}
// Process tasks asynchronously in parallel
const processedTasks = Promise.all(tasks.map(task => processTask(task)));
// Display the processed tasks
processedTasks.then(result => console.log('Processed Tasks:', result));
Process objects asynchronously in parallel using Promise.all().
Dynamic Object Filtering
// Sample array of objects
const employees = [
{ name: 'Alice', department: 'HR', salary: 50000 },
{ name: 'Bob', department: 'IT', salary: 60000 },
{ name: 'Charlie', department: 'IT', salary: 75000 }
];
// Function to dynamically filter objects based on a condition
function filterObjects(objects, conditionFn) {
return objects.filter(obj => conditionFn(obj));
}
// Example usage: Filter employees with a salary greater than 60000
const highSalaryEmployees = filterObjects(employees, employee => employee.salary > 60000);
// Display the filtered objects
console.log('High Salary Employees:', highSalaryEmployees);
Dynamically filter objects based on specified criteria using a flexible filtering function.
Object Mapping with Dynamic Transformation
// Sample array of objects
const products = [
{ id: 1, name: 'Laptop', price: 1200 },
{ id: 2, name: 'Smartphone', price: 800 },
{ id: 3, name: 'Tablet', price: 500 }
];
// Function to dynamically map and transform objects
function mapObjects(objects, transformFn) {
return objects.map(obj => transformFn(obj));
}
// Example usage: Add a discountedPrice property to each product
const productsWithDiscount = mapObjects(products, product => ({ ...product, discountedPrice: product.price * 0.9 }));
// Display the transformed objects
console.log('Products with Discount:', productsWithDiscount);
Dynamically transform objects based on a mapping function to create a new set of objects.
Advanced Object Sorting
// Sample array of objects
const books = [
{ title: 'Book C', author: 'Author 1', pages: 300 },
{ title: 'Book A', author: 'Author 2', pages: 250 },
{ title: 'Book B', author: 'Author 3', pages: 400 }
];
// Function for advanced object sorting based on pages
function sortByPages(objects) {
return objects.sort((a, b) => a.pages - b.pages);
}
// Example usage: Sort books by the number of pages
const sortedBooks = sortByPages(books);
// Display the sorted objects
console.log('Books Sorted by Pages:', sortedBooks);
Implement advanced sorting logic for an array of objects using a custom sorting function.