DEV Community

loading...
Cover image for When lodash is too much

When lodash is too much

davidlacarta profile image David Lacarta ・1 min read

It is not always necessary to use the well-known lodash utility library to do some basic operations with arrays and javascript objects.

Get safe object properties

function isObject(object) {
  return object && typeof object === "object";
}
function hasKey(object, key) {
  return key in object;
}

function safe(object) {
  return new Proxy(object, {
    get: (target, name) => {
      if (!hasKey(target, name)) {
        return "undefined";
      }
      if (!isObject(target[name])) {
        return target[name];
      }
      return safe(target[name]);
    }
  });
}

let's try...

const objectDeep = { a: { b: "x" } };
console.log(objectDeep.a.b);
// x
console.log(objectDeep.c.d);
// TypeError: Cannot read property 'd' of undefined
console.log(safe(objectDeep).a.b);
// x
console.log(safe(objectDeep).c.d);
// undefined

Get object's array unique

function isEqual(objectA, objectB) {
  return JSON.stringify(objectA) === JSON.stringify(objectB);
}

function unique(array) {
  return array.reduce((uniqueArray, currentElement) => {
    const isDuplicated = uniqueArray.find(element =>
      isEqual(element, currentElement)
    );
    return isDuplicated ? uniqueArray : [...uniqueArray, currentElement];
  }, []);
}

let's try...

console.log(unique([{ a: "x" }, { a: "z" }, { a: "x" }]));
// [ { a: 'x' }, { a: 'z' } ]

Get array one dimension less

function flat(array) {
  return [].concat.apply([], array);
}

let's try...

console.log(flat([["a", "b"], ["c", "d"]]));
// [ 'a', 'b', 'c', 'd' ]

Get clone object deep

function cloneDeep(object) {
  return JSON.parse(JSON.stringify(object));
}

let's try...

const objectDeep = { a: { b: "x" } };

const objectDeepClonedAssign = Object.assign(objectDeep);
objectDeep.a.b = "assign";
console.log(objectDeep);
// { a: { b: "assign" } }
console.log(objectDeepClonedAssign);
// { a: { b: "assign" } }

const objectDeepCloned = cloneDeep(objectDeep);
objectDeep.a.b = "deep";
console.log(objectDeep);
// { a: { b: "deep" } }
console.log(objectDeepCloned);
// { a: { b: "assign" } }

Discussion (2)

pic
Editor guide
Collapse
anduser96 profile image
Andrei Gatej

Thank you for sharing!

I'd like to point out a case when comparing 2 objects with JSON.stringify() could lead to unexpected results:

function isEqual(objectA, objectB) {
  return JSON.stringify(objectA) === JSON.stringify(objectB);
}

const a = { name: 'andrei', age: 18}
const b = { age: 18, name: 'andrei' }

console.log(isEqual(a,b)) // false

As far as I can understand, the order matters.
I didn't know about this a while ago, so I thought it was worth sharing.

Collapse
davidlacarta profile image
David Lacarta Author

Thank you for point out it!