What's the quickest way to rename all property names in a Javascript object?

对着背影说爱祢 提交于 2020-01-30 13:23:13

问题


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 b = {
   something_prop1: "val1",
   something_prop2: "val2",
   something_prop3: "val3",
   something_prop4: "val4",
}

Is there any way to achieve this without having to create an intervening array of keys or running a for or foreach loop?


回答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);



回答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);



回答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",
}

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

const b = transformKeys(a);

console.log(b);


来源:https://stackoverflow.com/questions/54921156/whats-the-quickest-way-to-rename-all-property-names-in-a-javascript-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!