[英]Getting values from json in JavaScript
If I have some json like this:如果我有这样的 json:
{
"dcf93893d83e4f28953f140b9cba1963":{
"foo":{
"client":"127.0.0.1",
"id":"31971",
"start time":1654131724.160335
},
"bar":{
"client":"127.0.0.1",
"id":"23456",
"start time":1654131900.997766
}
}
}
I figured out how to loop through it like this:我想出了如何像这样循环它:
for (var key in json) {
if (json.hasOwnProperty(key)) {
console.log(json[key])
}
}
How can I loop through each sub element (foo and bar in this case) and then fetch a key, for example id?我如何遍历每个子元素(在本例中为 foo 和 bar)然后获取一个键,例如 id?
client, id and start time are the only known key names client、id 和 start time 是唯一已知的键名
Expected output:预计 output:
31971
23456
EDIT: The json comes from fetch:编辑:json 来自 fetch:
setInterval(function () {
fetch(<url>)
.then(function (response) {
return response.json();
})
.then(function (json) {
for (var key in json) {
if (json.hasOwnProperty(key)) {
console.log(json[key])
}
}
})
}, 2000);
Do another loop and grab the inner values by key name:做另一个循环并通过键名获取内部值:
const json = { "dcf93893d83e4f28953f140b9cba1963":{ "foo":{ "client":"127.0.0.1", "id":"31971", "start time":1654131724.160335 }, "bar":{ "client":"127.0.0.1", "id":"23456", "start time":1654131900.997766 } } } for (var key in json) { if (json.hasOwnProperty(key)) { //console.log(json[key]) for(var key2 in json[key]) { console.log(json[key][key2]["id"]) } } }
You have to loop in each loop.你必须在每个循环中循环。 and save each id into an array.并将每个 id 保存到一个数组中。
var ids = []
for (var key in json) {
if (json.hasOwnProperty(key)) {
for(var obj in json[key]) {
if (obj.id) ids.push(obj.id)
}
}
}
Instead of iterating, you could just get the object's values with Object.values()
, and map those accordingly using flatMap()
and map()
:您可以使用Object.values()
和 map 获取对象的值,而不是迭代,相应地使用flatMap()
和map()
:
const data = { "dcf93893d83e4f28953f140b9cba1963": { "foo": { "client": "127.0.0.1", "id": "31971", "start time": 1654131724.160335 }, "bar": { "client": "127.0.0.1", "id": "23456", "start time": 1654131900.997766 } } }; const result = Object.values(data).flatMap(v => Object.values(v)).map(({id}) => id); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.