Search code examples
javascriptobjectjavascript-objectsmap-function

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


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

In this case First Name is a key with space, apparently when passed as above it causes error. How to handle this scenario?


Solution

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