gpt4 book ai didi

JavaScript - 循环 JSON 数组并匹配子数组中的字符串

转载 作者:行者123 更新时间:2023-11-30 10:05:23 24 4
gpt4 key购买 nike

我有带子数组的 JSON 数组,我想循环它并查找用户的用户名是否为“admin”。如果是,则创建包含属于用户“admin”(地区、运动、城市等)的数据的 JSON 数组。我不知道如何在循环中找到它然后切片。很抱歉提出愚蠢的问题,但我有点迷茫。

这是 JSON 数组,具有我所拥有的结构:

[
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
},
{
"_id": "552010740628cab002b3a700",
"region": {
"_id": "551e67b6d8f1afa01bd8652f",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "Bill",
"lastName": "Foo",
"username": "bill_foo",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e5e01abb74a8423410b88",
"nazev": "Hockey"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "some_title",
"created": "2015-04-04T16:25:24.733Z"
}
]

编辑:用户“admin”的预期结果是:

[
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
}]

最佳答案

遍历数组并提取用户名为 admin 的每个项目:

var result = [];
var nameToSearchFor = 'admin';

for(var index = 0; index < arr.length; index++)
{
var item = arr[index];
if(item.user.username === nameToSearchFor)
{
result.push(item);
}
}

关于JavaScript - 循环 JSON 数组并匹配子数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29456063/

24 4 0
文章推荐: java - AutocompleteSupportFragment.setPlaceFields 在启动时粉碎 App
文章推荐: javascript - jQuery scrollTop - 哈希值错误的问题
文章推荐: java - 是否可以避免 IntelliJ IDEA 中的自动换行?
文章推荐: javascript - 如何使背景图片的
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com