[英]Javascript/jQuery to get subarray value with random array key
我在 JSON 数据下面有这些:
{
"0": {
"jQuery331045811028719032642": {
"stepCount": 1,
"captionSize": 0,
"countdown": true,
"countdownAlertLimit": 10,
"displayCaptions": false,
"displayDays": 0,
"displayHours": true,
"fontFamily": "Verdana, sans-serif",
"fontSize": 0,
"lang": "en",
"languages": {},
"seconds": 2609,
"start": true,
"theme": "white",
"width": 4,
"height": 30,
"gap": 11,
"vals": [0, 0, 4, 3, 2, 9],
"limits": [2, 9, 5, 9, 5, 9],
"iSec": 5,
"iHour": 1,
"tickTimeout": 1000,
"intervalId": 1,
"tickCount": 0,
"timeTo": "2021-06-12T15:14:00.000Z",
"options": {
"timeTo": "2021-06-12T15:14:00.000Z",
"start": true,
"theme": "white",
"seconds": 2609
},
"sec": 2609,
"ttStartTime": 1623508230144
},
"jQuery331045811028719032641": {
"hasDataAttrs": true
}
},
"length": 1
}
假设上面的数组变量是var data
;
对于这个子jQuery331045811028719032642
是自动生成的。
我的问题,如何使用 jQuery 获取seconds
数组值?
我试过这个:
alert(data[0].seconds);
但它返回未定义。
您可以尝试使用此代码
const arrayData = Object.values(data["0"]);
console.log(arrayData[0].seconds);
您可以使用Object.values获取seconds
const data = { "0": { jQuery331045811028719032642: { stepCount: 1, captionSize: 0, countdown: true, countdownAlertLimit: 10, displayCaptions: false, displayDays: 0, displayHours: true, fontFamily: "Verdana, sans-serif", fontSize: 0, lang: "en", languages: {}, seconds: 2609, start: true, theme: "white", width: 4, height: 30, gap: 11, vals: [0, 0, 4, 3, 2, 9], limits: [2, 9, 5, 9, 5, 9], iSec: 5, iHour: 1, tickTimeout: 1000, intervalId: 1, tickCount: 0, timeTo: "2021-06-12T15:14:00.000Z", options: { timeTo: "2021-06-12T15:14:00.000Z", start: true, theme: "white", seconds: 2609, }, sec: 2609, ttStartTime: 1623508230144, }, jQuery331045811028719032641: { hasDataAttrs: true, }, }, length: 1, }; const zeroObj = data["0"]; const result = Object.values(zeroObj)[0].seconds; console.log(result);
您可以尝试其中任何一个来获取秒值。
1-使用 Object.values 获取 Object 中的值,如下所示
let res = Object.values(data["0"]);
let seconds = res.seconds; // This will give you value of seconds.
2- 使用 Object.keys 获取 object 的密钥并使用该密钥获取数据。
let keys = Object.keys(data[0]);
let seconds = data[0][keys[0]].seconds;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.