how to access object value witch '@' in key

63 Views Asked by At

i know this may be stupid question but how can i access value of object that has '@' in it key

{
  id: 'v6y4fra9dd3xxys',
  created: '2022-10-29 08:48:12.585',
  updated: '2022-11-14 08:03:46.477',
  '@collectionId': 'x16irtg922kc0cg',
  '@collectionName': 'products',
  condition: 'new',
  image: 'short4.jpg',
  name: 'Short 4',
  price: 19000,
  productImg: 'short4_iKD5NIhZWX.jpg',
  quantity: 1,
  type: 'shortboard',
  '@expand': {}
}

i want to use collectionName but don't know how to access it. i try but it got Unexpected character '@' error. what i supposed to do

2

There are 2 best solutions below

1
On

The best way to access your object is the following:


    try {
        if (Object['@collectionId'])
         //Do whatever with Object['@collectionId'];
    }catch(err){
        console.log(err)
    }

Using try catch block since you cannot use the optional attribute (Object?.@collectionId).

0
On

only for @collectionId you can use obj['@collectionId']

obj = {
  id: 'v6y4fra9dd3xxys',
  created: '2022-10-29 08:48:12.585',
  updated: '2022-11-14 08:03:46.477',
  '@collectionId': 'x16irtg922kc0cg',
  '@collectionName': 'products',
  condition: 'new',
  image: 'short4.jpg',
  name: 'Short 4',
  price: 19000,
  productImg: 'short4_iKD5NIhZWX.jpg',
  quantity: 1,
  type: 'shortboard',
  '@expand': {}
}

console.log("Values with @ : ", obj['@collectionId'])

or for all @ keys

obj = {
  id: 'v6y4fra9dd3xxys',
  created: '2022-10-29 08:48:12.585',
  updated: '2022-11-14 08:03:46.477',
  '@collectionId': 'x16irtg922kc0cg',
  '@collectionName': 'products',
  condition: 'new',
  image: 'short4.jpg',
  name: 'Short 4',
  price: 19000,
  productImg: 'short4_iKD5NIhZWX.jpg',
  quantity: 1,
  type: 'shortboard',
  '@expand': {}
}

atKeys = Object.keys(obj).filter(item => item.includes("@"))
console.log("Keys with @ : ", atKeys);
atKeys.forEach(item => {
  console.log("Values with @ : ", item, obj[item])
})