Categories
Lodash

Learning JavaScript by Implementing Lodash Methods — Objects and Collections

Spread the love

Lodash is a very useful utility library that lets us work with objects and arrays easily.

However, now that the JavaScript standard library is catching up to libraries such as Lodash, we can implement many of the functions in simple ways.

In this article, we’ll look at how to implement methods for checking if something exists in a collection and dealing with objects.

some

The Lodash some method returns a boolean to indicate if an item that meets the condition in the predicate exists in a collection.

For arrays, we can use the plain JavaScript array’s some method to search for an item and returns true is the item with the given condition is found.

We can implement some with the plain JavaScript’s some method as follows:

const some = (collection, predicate) => {
  return collection.some(predicate);
}

In the code above, we just used the array instance’s some method and pass in the predicate .

Then when we run some as follows:

const users = [{
    'user': 'foo',
    'active': true
  },
  {
    'user': 'bar',
    'active': false
  }
];
const result = some(users, u => u.active);

result is true since there’s an entry of users with active set to true .

castArray

The Lodash castArray method converts any object to an array. It takes a list of arguments and puts them all in an array.

With the rest operator, we can put the items in an array without much work. We can implement the castArray method as follows:

const castArray = (...args) => args;

In the code above, we just used the rest operator with args , which converts the list of arguments to an array, and then returned it directly.

Then when we call our castArray function as follows:

const result = castArray(1, 2, 3);

Then we get that result is:

[
  1,
  2,
  3
]

clone

The Lodash clone method returns a shallow copy of an object. It supports cloning all kinds of objects, including arrays, buffers, booleans, and date objects.

Since JavaScript has the spread operator for objects, we can just use that to do the cloning as follows:

const clone = obj => ({
  ...obj
});

Then we can call the clone function as follows:

const result = clone({
  a: 1
});

Then we see that result is:

{
  "a": 1
}

cloneDeep

The Lodash cloneDeep method recursively clones an object. With the spread operator, we can just recursively clone each level of an object ourselves.

For instance, we can implement that as follows:

const cloneDeep = (obj, cloned = {}) => {
  if (Array.isArray(obj)) {
    cloned = [
      ...obj
    ];
    for (let i = 0; i < obj.length; i++) {
      cloneDeep(obj[i], cloned[i]);
    }
  } else if (typeof obj === 'object') {
    cloned = {
      ...obj
    };
    for (const p of Object.keys(obj)) {
      cloneDeep(obj[p], cloned[p])
    }
  }
  return cloned;
}

In the code above, we have our own cloneDeep function, which takes obj for the original object and the cloned object which has the cloned object.

We loop through the objects and call cloneDeep on them afterward.

If obj is an array, then we spread the array with the spread operator.

Otherwise, we can use the spread operator to clone obj into cloned at the top level.

Then we check that if obj is an object. If it is, then we can loop through the keys and calls cloneDeep in the lower level of an object.

In the end, we return cloned with the cloned object.

Then we can call our cloneDeep function as follows:

const obj = {
  a: 1,
  b: {
    c: 2
  }
}
const result = cloneDeep(obj);

Then we get that result is:

{
  "a": 1,
  "b": {
    "c": 2
  }
}

and:

result === obj

is false . We can also clone arrays as follows:

const obj = [{
  'a': 1
}, {
  'b': 2
}]
const result = cloneDeep(obj);

Then we get that result is the following array:

[
  {
    "a": 1
  },
  {
    "b": 2
  }
]

and:

result === obj

is still false .

Conclusion

We can use the plain JavaScript array’s some method to check if an object that meets the condition in a predicate exists in a collection.

To implement the castArray method, we can just use the rest operator on the arguments.

Finally, the clone and cloneDeep methods can be implemented with the spread operator. cloneDeep needs an array or object check before cloning each level.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *