簡體   English   中英

Javascript/jQuery 使用隨機數組鍵獲取子數組值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM