我得到一个跟随的物体
{
IuW1zvaSABwH4q: {
label: 'Random Image of TypeScript not relavent to coworking',
thumbId: 'd501-f-b601-c8b1-4bd995e',
schemaType: 'xman-assets-image-set'
}
}
现在,我要访问其中的thumbID的值,即 d501-f-b601-c8b1-4bd995e
但是我的根密钥似乎是动态/随机的(IuW1zvaSABwH4q),我该如何访问其中的值?
答案 0 :(得分:20)
您可以从对象获取值,然后访问所需的键。
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)
答案 1 :(得分:8)
您可以使用 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));
答案 2 :(得分:7)
假设只有一个属性,则可以通过第一个属性访问它。
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);
答案 3 :(得分:5)
您可以使用false
来迭代对象,然后检查该对象是否具有名称为null
的密钥。如果对象没有for..in
键
thumbId
答案 4 :(得分:4)
尝试
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);
}
}
答案 5 :(得分:3)
let yourObject = {
IuW1zvaSABwH4q: {
label: 'Random Image of TypeScript not relavent to coworking',
thumbId: 'd501-f-b601-c8b1-4bd995e',
schemaType: 'xman-assets-image-set'
}
}
_.pluck(_.values(yourObject),'thumbId');
// ["d501-f-b601-c8b1-4bd995e"]
您还可以使用_.first
安全地访问第一个数组元素
答案 6 :(得分:1)
结合使用另一种方法
dataProvider(GET_LIST, 'clicks', {
//
})
.then(response => this.setState({ [myWeekly]: response.data.count }))
/* ^^ This callback runs after the while block
By this time, myDaily === "AKdaily" */
和JSON.stringify()
split()
答案 7 :(得分:1)
var json = {
IuW1zvaSABwH4q: {
label: 'Random Image of TypeScript not relavent to coworking',
thumbId: 'd501-f-b601-c8b1-4bd995e',
schemaType: 'xman-assets-image-set'
},
IuW2zvaSABwH4q: {
label: 'Random Image of TypeScript not relavent to coworking',
thumbId: 'd501-f-b601-c8b1-4bd995e',
schemaType: 'xman-assets-image-set'
},
IuW3zvaSABwH4q: {
label: 'Random Image of TypeScript not relavent to coworking',
thumbId: 'd501-f-b601-c8b1-4bd995e',
schemaType: 'xman-assets-image-set'
}
}
for (var key in json) {
if (json[key]) {
for (var x in json[key]) {
if (x === 'thumbId') console.log(json[key][x]);
}
}
}
我使用两个嵌套的来提取thumbId。