Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing something inside the object when you don't know the key [duplicate]

Tags:

javascript

I am getting a following object

{
  IuW1zvaSABwH4q: {
    label: 'Random Image of TypeScript not relavent to coworking',
    thumbId: 'd501-f-b601-c8b1-4bd995e',
    schemaType: 'xman-assets-image-set'
  }
}

Now, I want to access the value of thumbID inside it i.e. d501-f-b601-c8b1-4bd995e

But my root key seems to be dynamic/random (IuW1zvaSABwH4q), How can I access the value inside it?

like image 994
anny123 Avatar asked Mar 05 '19 04:03

anny123


3 Answers

You can get the values from object and than access the desired key.

let obj =  {
    IuW1zvaSABwH4q: 
      {
        label: 'Random Image of TypeScript not relavent to coworking', 
        thumbId: 'd501-f-b601-c8b1-4bd995e',
        schemaType: 'xman-assets-image-set' 
      } 
    }
    
let op = Object.values(obj)[0].thumbId

console.log(op)
like image 97
Code Maniac Avatar answered Oct 29 '22 18:10

Code Maniac


You can use Array.map to transform it and Array.forEach to get it and print it in the console.

const obj = {
    IuW1zvaSABwH4q: {
        label: 'Random Image of TypeScript not relavent to coworking',
        thumbId: 'd501-f-b601-c8b1-4bd995e',
        schemaType: 'xman-assets-image-set'
    },
    YuW1zvaSABwH7q: {
        label: 'Random Image of TypeScript not relavent to coworking',
        thumbId: 'as90-f-b601-c8b1-4bd9958', 
        schemaType: 'xman-assets-image-set'
    }
};
//for one object
console.log(Object.values(obj)[0].thumbId);
//multiple unknown keys
Object.values(obj).map(ele => ele.thumbId).forEach(th=> console.log(th));
like image 41
Fullstack Guy Avatar answered Oct 29 '22 17:10

Fullstack Guy


Assuming there is only one property you could access it via the first property.

const obj = { IuW1zvaSABwH4q: 
      { label: 'Random Image of TypeScript not relavent to coworking', thumbId: 'd501-f-b601-c8b1-4bd995e', schemaType: 'xman-assets-image-set' 
       } 
    };
    
console.log(obj[Object.getOwnPropertyNames(obj)[0]].thumbId);
like image 45
Adrian Brand Avatar answered Oct 29 '22 16:10

Adrian Brand