说,我有一个看起来像这样的对象:
const a = {
prop1: "val1",
prop2: "val2",
prop3: "val3",
prop4: "val4",
}
我想从a
中得到这样的东西:
const b = {
something_prop1: "val1",
something_prop2: "val2",
something_prop3: "val3",
something_prop4: "val4",
}
有什么方法可以实现而不必创建中间的键数组或运行for
或foreach
循环吗?
答案 0 :(得分:4)
您可以映射新对象并使用Object.assign
和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);
答案 1 :(得分:2)
您可以这样做:
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);
答案 2 :(得分:1)
如果您不打算使用reduce
或for
,那么这里是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);