问题
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