DEV Community

Nir Adler
Nir Adler

Posted on • Originally published at blog.niradler.com on

Javascript object reamp

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' } 
}
*/

Enter fullscreen mode Exit fullscreen mode

for getting started install the package with npm:

npm i -S object-remap

Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay