【问题标题】:How to remove spaces of object's keys? [for...in] [keys.forEach] [reduce]如何删除对象键的空格? [for...in] [keys.forEach] [减少]
【发布时间】: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 },
]

问题:

  1. 我做得对吗?
  2. 还有其他解决方案可以解决我的任务吗?

我写了 3 个解决方案:for inObject.keys().forEachreduce

_

这是我的 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


【解决方案1】:

诸如“什么更好”之类的问题是主观的,答案通常是“只要能解决问题,什么最适合你”。然而,从长远来看,将代码分成可重用的部分会更干净,这是一个普遍的共识。在您的特定示例中,“修改某些对象的键”和“删除空格”是两个松散相关的部分,每个部分都可以单独使用,因此将它们编码为“更好”,例如:

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

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

    return res;
}

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

然后,要解决手头的问题,您只需将两个部分组合在一起:

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

【讨论】:

    【解决方案2】:

    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)

    【讨论】:

      【解决方案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 }
      ];
      
      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);

      【讨论】:

      • 您应该提供一些背景信息,说明您所做的更改,为什么您认为这是一种更好的方法等。
      • 你能在你的for循环的开头加上console.time,在结尾加上console.timeEnd吗?看看我的问题 - 我已经添加了这些
      【解决方案4】:

      您可以使用一些正则表达式来删除空格:

      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)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-12
        • 2014-05-26
        • 1970-01-01
        • 2018-04-14
        • 2015-07-13
        • 2015-12-24
        • 1970-01-01
        • 2018-06-29
        相关资源
        最近更新 更多