【问题标题】:Javascript - destructure object if some keys have spaces [duplicate]Javascript - 如果某些键有空格,则解构对象[重复]
【发布时间】:2020-12-14 15:20:04
【问题描述】:

我必须处理一个草率的对象data.fields,其中一些键有空格,一些没有,一些大写,一些没有。我一直在手动分配这样的变量:

const comments = data.fields["Additional Location Comments"];
const autoNumber = data.fields.Autonumber;
const category = data.fields.category;
const categorySymbol = data.fields["Category Symbol"];
const currentLocation = data.fields["Current Location"];
const dateModified = data.fields["Date Modified"];
const deliveryLocation = data.fields["Delivery Location"];
const description = data.fields.Desctiption;
const dimensions = data.fields.Dimensions;
const favorites = data.fields.Favorites;
const itemUrl = data.fields["ITEM URL"];
const image = data.fields.Image;

我将如何解构它并重命名键,使其变成这样?

const {
  additionalLocationComments,
  autoNumber,
  category,
  categorySymbol,
  currentLocation,
  dateModified,
  deliveryLocation,
  description,
  dimensions,
  favorites,
  itemUrl,
  image,
} = data.fields;

【问题讨论】:

标签: javascript object


【解决方案1】:

我会像下面那样做。最重要的方面是将给定字符串转换为其骆驼大小写等效项的函数:

function camelCase(s) {
    s = s.replace(/\b\w/g, m => m.toUpperCase())
         .replace(/[A-Z]{2,}/g, m => m[0] + m.slice(1).toLowerCase())
         .replace(/\W/g, "");
    return s[0].toLowerCase() + s.slice(1);
}

function cleanObject(obj) {
    return Object.fromEntries(Object.entries(obj).map(([k, v]) => [camelCase(k), v]));
}

let fields = {
    "Additional Location Comments": 1,
    "Autonumber": 2,
    "category": 3,
    "Category Symbol": 4,
    "Current Location": 5,
    "ITEM URL": 6,
    "alreadyInCamelCase": 7
};
console.log(cleanObject(fields));

【讨论】:

    【解决方案2】:

    您可以做的是遍历所有键,然后将它们转换为驼峰式大小写,并将旧键中的数据与新键相加。

    const oldob = {
      "A Test Thing" : 1,
      "Another Test" : 3,
      "Ok Heres Another" : 4
    };
    
    let newob = {};
    
    const camelCase = (str) => { 
                return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word,      index) 
                { 
                    return index == 0 ? word.toLowerCase() : word.toUpperCase(); 
                }).replace(/\s+/g, ''); 
            }
    
    Object.keys(oldob).forEach(key => {
      newob[camelCase(key)] = oldob[key];
    });
    
    console.log(newob);

    【讨论】:

      猜你喜欢
      • 2018-12-31
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 2015-05-03
      • 1970-01-01
      • 2020-04-11
      • 1970-01-01
      • 2021-11-24
      相关资源
      最近更新 更多