How to Destructure Object Properties with Key Names That Are Invalid Variable Names

How to destructure object properties with key names that are invalid variable names?

const data = {   "key-with-dash": ["BAZ"]}
const {"key-with-dash": foo} = data;
console.log("foo", foo);

Object destructuring with property names that are not valid variable names

You can assign it a valid variable name using this syntax:

var {"my name": myName, age} = obj2; 

// use myName here

Javascript - destructure object if some keys have spaces

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

How to destructure an object that contains key names with hyphen?

You need to rename the variable, because minus is an operator and not part of a variable name.

BTW, name is a property of Window.name. if this is used you need to rename this value as well.

const { name, 'last-name': lastName } = { name: 'foo', 'last-name': 'bar' };
console.log(lastName);

How to destructure an array with object that has space in its keys?

Variable names (identifiers) can't have spaces in them, you won't be able to destructure that property into a standalone variable unless you also rename the variable - which can be done using bracket notation:

data.map(({
ID,
filePath,
accountId,
companyId,
['First Name']: firstName,
...rest
}) => rest)

const data = [  {    'First Name': 'foo',    'anotherProp': 'another'  },  {    'First Name': 'bar',    'anotherProp': 'another'  }];
const mapped = data.map(({ ID, filePath, accountId, companyId, ['First Name']: firstName, ...rest}) => rest);
console.log(mapped);

JavaScript destructuring object containing fields with special characters

You could take a computed property and a new variable name.

let arr = [{ '@type': 'Something', data: 1234 }, { '@type': 'Something', data: 3214 }];
for (const { data, ['@type']: renamed } of arr) { console.log(renamed);}


Related Topics



Leave a reply



Submit