gpt4 book ai didi

javascript - 如何获取 JSON 数组中的 JSON 对象名称

转载 作者:行者123 更新时间:2023-11-28 17:34:07 24 4
gpt4 key购买 nike

我需要获取值“channelA”和“channelB”,它们是对象名称。

JSON 文件:

[
{
"channelA": {
"programmes": [
{
"start_utc": 1522208700,
"stop_utc": 1522209600,
},
{
"start_utc": 1522209600,
"stop_utc": 1522210800,
}
]
}
},
{
"channelB": {
"programmes": [
{
"start_utc": 1522256700,
"stop_utc": 1522260800
},
{
"start_utc": 152229000,
"stop_utc": 1522318900,
}
]
}
}
]

我将 JSON 存储在名为 epg 的值中,并使用以下命令迭代 epg:

for (var k = 0; k < epg.length; k++) {          
console.log(_epg[k]);
}

enter image description here

我需要将对象的名称与另一个变量(channelId)进行比较:

for (var k = 0; k < _epg.length; k++) {
if (channelId == epg[k]) {
console.log(_epg[k]);
}
}

最佳答案

为此使用 Object.keys() 方法:

let myArr = [
{
"channelA": {
"programmes": [
{
"start_utc": 1522208700,
"stop_utc": 1522209600,
},
{
"start_utc": 1522209600,
"stop_utc": 1522210800,
}
]
}
},
{
"channelB": {
"programmes": [
{
"start_utc": 1522256700,
"stop_utc": 1522260800
},
{
"start_utc": 152229000,
"stop_utc": 1522318900,
}
]
}
}
]

for (let item of myArr) {
for (let key of Object.keys(item)) {
if (key == "channelA" || key == "channelB") console.log(key + ": ", item[key])
}
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

关于javascript - 如何获取 JSON 数组中的 JSON 对象名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49555664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com