Nir Adler
Piece by Piece

Follow

Piece by Piece

Follow
Javascript object reamp

Photo by Nick Fewings on Unsplash

Javascript object reamp

Nir Adler's photo
Nir Adler
ยทFeb 11, 2020ยท
Play this article

in my daily job as a full stack js developer I often need to manipulate js objects, either remove fields or transform to a new structure etc.

I decided to create an npm module object-remap, to make this repeated task more reliable, reduce code, and create cleaner code.

let's look at the examples:

const objectRemap = require("object-remap");

const obj = {
  a: 1,
  b: 2,
  c: 3,
  d: {
    e: 4,
    f: [1, 2, 3]
  }
};

//simple usage
const fields = ["a", "b", "c"];

let newObj = objectRemap(obj, fields);
console.log({ obj, newObj });
/*
{
  obj: { a: 1, b: 2, c: 3, d: { e: 4, f: [Array] } },
  newObj: { a: 1, b: 2, c: 3}
}
*/

//advance usage
const fieldsMap = [
  {
    origin: "a",
    target: "a"
  },
  {
    origin: "d.e",
    target: "e"
  },
  {
    origin: "d.f",
    target: "f",
    formatter: data => `${data.length} items`
  }
];

newObj = objectRemap(obj, fieldsMap);
console.log({ obj, newObj });
/*
{ 
  obj: { a: 1, b: 2, c: 3, d: { e: 4, f: [Array] } },
  newObj: { a: 1, e: 4, f: '3 items' } 
}
*/

for getting started install the package with npm:

npm i -S object-remap
ย 
Share this