gpt4 book ai didi

javascript - 如何使用JavaScript过滤JSON

转载 作者:行者123 更新时间:2023-12-02 07:17:42 25 4
gpt4 key购买 nike

我需要根据其值过滤一个巨大的JSON文件。

这是我的JSON代码(这是我的JSON对象的一部分,实际上,它有1000多个)。

var jsonObject = [  
{
"UserId":10259,
"FullName":"hello world",
"CustomerId":"10165"
},
{
"UserId":10405,
"FullName":"test value",
"CustomerId":"10261"
},
{
"UserId":10400,
"FullName":"mark ant",
"CustomerId":"10161"
},
{
"UserId":16224,
"FullName":"jhon cena",
"CustomerId":""
},
{
"UserId":10416,
"FullName":"shoze ahh",
"CustomerId":"1"
},
{
"UserId":10244,
"FullName":"kajal man",
"CustomerId":"10"
}
];

为了过滤上述JSON对象,我使用了以下过滤器功能。
function usersBasedOnIDs(CustomerIds) {
if (CustomerIds == "") {
console.log(jsonObject);
} else if (CustomerIds == "9999xx") {

let result = jsonObject.filter(c => c.CustomerId == "");
console.log(result);
} else {
let result = jsonObject.filter(c => c.CustomerId != "" && CustomerIds.includes(c.CustomerId));
console.log(result);
}
}

我如何调用该函数
usersBasedOnIDs("");
usersBasedOnIDs("10261,10165");
usersBasedOnIDs("9999xx");

我的代码有几个问题,
  • 此功能不适用于IE 11早期版本
  • 还有另一件事是,当我将函数调用为usersBasedOnIDs("10261,10165");usersBasedOnIDs("10261");时,其返回以下JSON输出
    {UserId: 10405, FullName: "test value", CustomerId: "10261"}
    {UserId: 10416, FullName: "shoze ahh", CustomerId: "1"}
    {UserId: 10244, FullName: "kajal man", CustomerId: "10"}

  • 但是我的期望是,只有这个
    {UserId: 10405, FullName: "test value", CustomerId: "10261"}

    怎样才能更改功能以避免 这两个问题

    最佳答案

    因此,这是基于@adiga答案的IE 11的完整答案。将箭头功能更改为普通功能,并使用 Array.indexOf 而不是includes

    const array = [
    { UserId: 10259, FullName: "hello world", CustomerId: "10165" },
    { UserId: 10405, FullName: "test value", CustomerId: "10261" },
    { UserId: 10400, FullName: "mark ant", CustomerId: "10161" },
    { UserId: 16224, FullName: "jhon cena", CustomerId: "" },
    { UserId: 10416, FullName: "shoze ahh", CustomerId: "1" },
    { UserId: 10244, FullName: "kajal man", CustomerId: "10" }
    ];

    function usersBasedOnIDs(CustomerIds) {
    if (CustomerIds === "") return array;

    if (CustomerIds == "9999xx") {
    return array.filter(function(c) {
    return c.CustomerId == "";
    });
    }

    const ids = CustomerIds.split(",");
    return array.filter(function(c) {
    return c.CustomerId !== "" && ids.indexOf(c.CustomerId) > -1;
    });
    }

    console.log(usersBasedOnIDs("10261,10165"))

    关于javascript - 如何使用JavaScript过滤JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56800624/

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