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

后端 未结 3 404
不知归路
不知归路 2021-01-29 11:44

Say, I have an object that looks like this:

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

And I wan

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-29 12:33

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

提交回复
热议问题