1. User Profile Update
Update an object property and add a new one.
const user = {
name: "Vijay",
age: 25,
email: "vijay@gmail.com"
};
user.email = "vijaykumar@gmail.com";
user.isActive = true;
console.log(user);
Output:
{
name: "Vijay",
age: 25,
email: "vijaykumar@gmail.com",
isActive: true
}
2. Shopping Cart Total
Calculate total price from an array of objects.
const cart = [
{ name: "Shirt", price: 500 },
{ name: "Shoes", price: 1500 },
{ name: "Cap", price: 300 }
];
const total = cart
.map(val => val.price)
.reduce((acc, val) => acc + val, 0);
console.log(total);
Output:
2300
3. Find Specific Object
Find a user with a specific name.
const users = [
{ name: "Vijay", age: 25 },
{ name: "Arun", age: 30 },
{ name: "Kumar", age: 28 }
];
const output = users.filter(n => n.name === "Arun");
console.log(output);
Output:
[{ name: "Arun", age: 30 }]
4. Add Item to Array & Filter
Add a new product and filter data.
const products = [
{ name: "Shirt", price: 500 },
{ name: "Shoes", price: 1500 }
];
products.push({ name: "Pant", price: 1750 });
console.log(products);
const newProdut = products.filter(
n => n.name !== "Shoes" && n.price > 1000
);
console.log(newProdut);
Output:
[
{ name: "Shirt", price: 500 },
{ name: "Shoes", price: 1500 },
{ name: "Pant", price: 1750 }
]
[
{ name: "Pant", price: 1750 }
]
5. Count Items in Object
Find total values inside an object.
const fruits = {
apple: 2,
banana: 5,
mango: 3
};
const output = Object.values(fruits).reduce((acc, n) => acc + n);
console.log(output);
Output:
10
6. Convert Array to Object
Convert array into object with values as keys.
const users = ["Vijay", "Arun", "Kumar"];
const dub = Object.fromEntries(
users.map(v => [v, true])
);
console.log(dub);
Output:
{
Vijay: true,
Arun: true,
Kumar: true
}
Top comments (1)
Much simpler:
Your version returns an array containing the user. This version returns the found user (which is probably preferable), and stops looking when the user is found - more efficient: