【发布时间】:2019-03-25 13:51:56
【问题描述】:
我的目标:从对象的键中删除空格。
比如我有这样的记录:
const records = [
{ 'Red Blue': true, 'Orange Strawberry': true, 'Abc Xyz': true },
{ 'Blue Red': true, 'Abc Abc': true, 'Abc Xyz': true },
{ 'Yellow Green': true, 'Apple Banana': true, 'Abc Xyz': true },
]
并且必须删除每个记录的每个键的空格,就像:
[
{ 'RedBlue': true, 'OrangeStrawberry': true, 'AbcXyz': true },
{ 'BlueRed': true, 'AbcAbc': true, 'AbcXyz': true },
{ 'YellowGreen': true, 'AppleBanana': true, 'AbcXyz': true },
]
问题:
- 我做得对吗?
- 还有其他解决方案可以解决我的任务吗?
我写了 3 个解决方案:for in、Object.keys().forEach 和 reduce。
_
这是我的 3 个解决方案:
const records = [
{ "Red Blue": true, "Orange Strawberry": true, "Abc Xyz": true },
{ "Blue Red": true, "Abc Abc": true, "Abc Xyz": true },
{ "Yellow Green": true, "Apple Banana": true, "Abc Xyz": true },
];
/* 1) for...in */
console.time && console.time('solution 1');
const solution1 = records.map(record => {
const newRecord = {};
for (const key in record) {
newRecord[key.replace(/\s/g, "")] = record[key];
}
return newRecord;
});
console.timeEnd && console.timeEnd('solution 1');
/* 2) Object.keys(records).forEach */
console.time && console.time('solution 2');
const solution2 = records.map(parent => {
const newParent = {};
Object.keys(parent).forEach(key => {
newParent[key.replace(/\s/g, "")] = parent[key];
});
return newParent;
});
console.timeEnd && console.timeEnd('solution 2');
/* 3) reduce */
console.time && console.time('solution 3');
const solution3 = records.map(parent => {
return Object.keys(parent).reduce((acc, key) => ({
...acc,
[key.replace(/\s/g, "")]: parent[key],
}), {});
});
console.timeEnd && console.timeEnd('solution 3');
/* All solutions has the same result */
console.log({
solution1,
solution2,
solution3,
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
更新:添加了console.time 来衡量每个解决方案的执行时间。
【问题讨论】:
-
您的问题是关于循环而不是删除空格
-
@guijob 我想你在标题方面是对的,但是一个问题比实际要解决的问题要好得多,而不是询问解决方案本身 - 避免 XY 问题.
-
你三次问自己是否可以做到,但你从来没有问过自己是否应该这样做。
-
@Vic 为什么从属性名称中删除空格是他“不应该做的”......?为什么不在您的评论中包含这一点,而不是在不为此类声明提供基础的情况下含糊地告诉他您不同意?
-
@TylerRoper 为了不避免 XY 问题我写了第二个问题 ;)
标签: javascript arrays ecmascript-6 transformation reduce