Skip to content Skip to sidebar Skip to footer

What's The Quickest Way To Rename All Property Names In A Javascript Object?

Say, I have an object that looks like this: const a = { prop1: 'val1', prop2: 'val2', prop3: 'val3', prop4: 'val4', } And I want something like this derived from a: const

Solution 1:

You could map new objects and build a single object with Object.assign and spread syntax ....

const
    a = { prop1: "val1", prop2: "val2", prop3: "val3", prop4: "val4" },
    b = Object.assign(...Object.entries(a).map(([k, v]) => ({ ['something_' + k]: v })));

console.log(b);

Solution 2:

You can do:

const a = {
  prop1: "val1",
  prop2: "val2",
  prop3: "val3",
  prop4: "val4",
};
const b = {};
Object.keys(a).forEach(k => b[`something_${k}`] = a[k]);

console.log(b);

Solution 3:

Here is an example with reduce if your point is not to use for or forEach.

const a = {
  prop1: "val1",
  prop2: "val2",
  prop3: "val3",
  prop4: "val4",
}

consttransformKeys = obj => Object.keys(obj).reduce((acc, key) => (acc[`something_${key}`] = obj[key], acc), {});

const b = transformKeys(a);

console.log(b);

Post a Comment for "What's The Quickest Way To Rename All Property Names In A Javascript Object?"