Like many programming languages, JavaScript has its flaws and quirks. Built-in functions or syntax you think should be there just isn’t. Output from even the most basic input can border on insanity (what’s true + true ?). Even basic things like loops behave differently than one might expect.

Though JavaScript behaves strangely from time to time, it is still one of the most widely used languages today. Sometimes all we need is a little help with those repetitive, simple tasks that come up each day. I’ve put together a list of a few common problems to solve with their corresponding solutions in JS. Let’s get into it.

Note: many of these examples use ES6 and are not plain vanilla JavaScript. Depending on what framework you’re working with you may or may not be able to use ES6 syntax.

1. Finding a specific object in an array of objects

This is arguably one of the most common tasks you’ll need to accomplish in the JS world. Iterating through an array of objects to find a specific one. The find method is our friend here. Simply plugin the selection criteria using an anonymous function as the argument and you’re set:

let customers = [
  { id: 0, name: 'paul' },
  { id: 1, name: 'jeff' },
  { id: 2, name: 'mary' }
];
let customer = customers.find(cust => cust.name === 'jeff');
console.log(customer);
--> { id: 1, name: 'jeff' }

2. Looping over an object’s keys and values

Sometimes your data structure might be a complex object that contains a bunch of key/value pairs. Iterating over each pair is a little odd at first glance depending on what languages you’re used to but its straightforward once you get used to using the functions of Object.

After you grab the objects keys you can loop through the keys and values at the same time. In this example you have access to each pair using the key and value variables during the loop.

let myObject = { one: 1, two: 2, three: 3 };

Object.keys(myObject).forEach((key, value) => {
  //...do something
  console.log(key, value);
});

#javascript #programming #developer

6 JavaScript Code Snippets For Solving Common Problems
63.70 GEEK