简体   繁体   English

如何删除对象键的空格? [for…in] [keys.forEach] [reduce]

[英]How to remove spaces of object's keys? [for…in] [keys.forEach] [reduce]

My goal: remove spaces from keys of objects. 我的目标:从对象键中删除空格。

For example, I have such records: 例如,我有这样的记录:

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 },
]

And have to remove spaces of each key of each record, to be like: 并且必须删除每个记录的每个键的空格,就像:

[
    { 'RedBlue': true, 'OrangeStrawberry': true, 'AbcXyz': true },
    { 'BlueRed': true, 'AbcAbc': true, 'AbcXyz': true },
    { 'YellowGreen': true, 'AppleBanana': true, 'AbcXyz': true },
]

Questions: 问题:

  1. Am I doing right? 我说的对吗?
  2. Is there another solution that can solve my task? 还有其他解决方案可以解决我的任务吗?

I wrote 3 solutions: with for in , with Object.keys().forEach and with reduce . 我写了3个解决方案: for inObject.keys().forEach以及reduce

_ _

Here 3 solutions of mine: 这是我的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; } 

UPDATED: added console.time to measure the execution time of each solution. 更新:添加console.time来衡量每个解决方案的执行时间。

Questions like "what is better" are subjective and the answer is usually "whatever fits you the best as long as it does the trick". 诸如“什么更好”之类的问题是主观的,答案通常是“只要能解决问题,最适合您”。 However, there's a common consensus that separating code into reusable parts is cleaner in the long run. 但是,有一个普遍共识是,从长远来看,将代码分成可重用的部分会更清洁。 In your particular example, "modify the keys of some object" and "remove whitespace" are two loosely related parts, which each can be useful on its own, so it's "better" to code them as such, for example: 在您的特定示例中,“修改某个对象的键”和“删除空白”是两个松散相关的部分,每个部分都可以单独使用,因此“更好地”对它们进行这样的编码,例如:

function mapKeys(obj, fn) {
    let res = {};

    for (let [k, v] of Object.entries(obj))
        res[fn(k)] = v;

    return res;
}

and

let removeSpaces = x => x.replace(/\s+/g, '');

Then, to solve the problem at hand, you just combine both parts together: 然后,要解决当前的问题,只需将两个部分组合在一起:

newRecords = records.map(rec => mapKeys(rec, removeSpaces))

 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 } ]; console.time && console.time('Execution time'); for (let record of records) { for (let key in record) { record[key.split(' ').join('')] = record[key]; if (key.split(' ').join('') !== key) delete record[key]; } } console.timeEnd && console.timeEnd('Execution time'); console.log(records); 

 const records = [ { "Red Blue": true, "Orange Strawberry": true, "Abc Xyz": true, hello: 'world' }, { "Blue Red": true, "Abc Abc": true, "Abc Xyz": true }, { "Yellow Green": true, "Apple Banana": true, "Abc Xyz": true }, ] console.time && console.time('Execution time'); const newRecords = records.map(r => { const rKeys = Object.keys(r) let refObj = {} rKeys.forEach(k => { let tempKey = k if (k.indexOf(' ') !== -1) tempKey = k.replace(' ', '') refObj[tempKey] = r[k] }) return refObj }); console.timeEnd && console.timeEnd('Execution time'); console.log(newRecords) 

You can use some regex to remove spaces: 您可以使用一些正则表达式删除空格:

 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 }, ] const noSpaces = JSON.parse(JSON.stringify(records).replace(/\\s(?=\\w.+":)/gm, '')) console.log(noSpaces) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM