2

I have to handle a sloppy object data.fields where some of the keys have spaces, some don't, some are capitalized, some not. I've been manually assigning vars like this:

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;

How would I destructure this and rename the keys so it would be something like this?

const {
  additionalLocationComments,
  autoNumber,
  category,
  categorySymbol,
  currentLocation,
  dateModified,
  deliveryLocation,
  description,
  dimensions,
  favorites,
  itemUrl,
  image,
} = data.fields;
Kirk Ross
  • 6,413
  • 13
  • 61
  • 104
  • 3
    Does this answer your question? [How to destructure object properties with key names that are invalid variable names?](https://stackoverflow.com/questions/38762715/how-to-destructure-object-properties-with-key-names-that-are-invalid-variable-na) – Nate Levin Aug 25 '20 at 21:18

2 Answers2

0

What you can do is loop through all of the keys then convert them into camel case and add the data with those from the old keys with the new ones.

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);
Ameer
  • 1,980
  • 1
  • 12
  • 24
-1

I would do it like below. The most important aspect is a function that turns a given string to its camel case equivalent:

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));
trincot
  • 317,000
  • 35
  • 244
  • 286