[英]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
:我想要这样的东西来自
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?有没有什么方法可以实现这一点,而不必创建中间的键数组或运行
for
或foreach
循环?
You could map new objects and build a single object with Object.assign
and spread syntax ...
.您可以映射新对象并使用
Object.assign
和spread 语法构建单个对象...
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);
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);
Here is an example with reduce
if your point is not to use for
or forEach
.如果您的观点是不使用
for
或forEach
则这是一个使用reduce
的示例。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.