当您不知道键时访问对象内部的某些内容

ann*_*123 22 javascript

我得到以下对象

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

现在,我想访问其中的thumbID的值,即d501-f-b601-c8b1-4bd995e

但是我的根密钥似乎是动态/随机的(IuW1zvaSABwH4q),如何访问其中的值?

Cod*_*iac 20

您可以从object获取值,然后访问所需的键。

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)
Run Code Online (Sandbox Code Playgroud)

  • 我认为OP是指`IuW1zvaSABwH4q`密钥,而不是`thumbId` (2认同)

Ful*_*Guy 9

您可以使用Array.map它进行转换,并Array.forEach在控制台中进行打印。

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));
Run Code Online (Sandbox Code Playgroud)


Adr*_*and 6

假设只有一个属性,则可以通过第一个属性访问它。

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);
Run Code Online (Sandbox Code Playgroud)


brk*_*brk 5

您可以使用for..in来迭代对象,然后检查该对象是否具有名称键thumbId。如果对象没有thumbId密钥,此检查将确保代码不会引发错误

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


for (let keys in obj) {
  if (obj[keys].hasOwnProperty('thumbId')) {
    console.log(obj[keys].thumbId);
  }
}
Run Code Online (Sandbox Code Playgroud)