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

时间:2019-03-25 13:51:56

标签: javascript arrays ecmascript-6 transformation reduce

我的目标:从对象键中删除空格。

例如,我有这样的记录:

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来衡量每个解决方案的执行时间。

4 个答案:

答案 0 :(得分:2)

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

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))

答案 1 :(得分:1)

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);

答案 2 :(得分:1)

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 :(得分:0)

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

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)