如果一个值在一个数组中,如果大小写不在't匹配,请将其替换为新值

Check case insentively if a value is in an array, and if the case doesn't match, replace it with the new value

本文关键字:一个 如果 匹配 新值 替换 大小写 数组      更新时间:2023-09-26

我正试图用正确的区分大小写替换数组中的值。这是因为我正在尝试更正用户输入。我从页面中检索到正确的大小写,用户将有一个值数组,其中一些值是不正确的。

例如:

userValues = ["apple321", "orange_22", "pineApple" , "Cantelope", "grASShopper_9000"];
var value1 = "Apple321";
var value2 = "orange_22";
var value3 = "Cantelope";
var value4 = "GrassHopper_9000";

然后,在某个函数运行完所有值后,结果将是:

userValues = ["Apple321", "orange_22", "pineApple" , "Cantelope", "GrassHopper_9000"];

我之所以有value1value2等,是因为我已经创建了一个循环来运行对象。只是不确定如何比较结果值。然而,以下是我已经掌握的:

// When the user enters data, it's sometimes case insensitive. This normalizes the data.
function NormalizeData(downloaded_data)
{
    $.each(downloaded_data, function(website,streams){
        $.each(streams, function(stream_name,value){
            stream_list[website] // This is the global variable array
            value.displayName; // This is the value I need to check case sensitivity, and replace with the new case if different
        });
    });
}

以下是请求的数据结构:

downloaded_data = {
    twitch_tv : {
        timthetatman : {
            Online: "1",
            Website: "twitch_tv",
            displayName: "TimTheTatman"
        }
    }
}
streamlist = {
    twitch_tv : {
        ["timthetatman"]
    }
    hitbox_tv: {
        []
    }
}

我想明白了。由于我使用的是一个数组来表示我想要更改的值,而不是一个对象,所以它实际上比我想象的要简单得多。我对每个值都运行了一个循环,如果两个值的小写字母匹配,但非小写字母的值不匹配,我在数组中替换它,使用数字键作为引用。

function NormalizeData(downloaded_data)
{   
    $.each(downloaded_data, function(website,streams){
        $.each(streams, function(stream_name,value){
            $.each(stream_list[website], function(arrKey,arrVal){
                if(arrVal.toLowerCase() == stream_name.toLowerCase() && stream_list[website][arrKey] !== value.displayName)
                    stream_list[website][arrKey] = value.displayName;
            });
        });
    });
}

这里,简单地说,如果数组被称为Array1,并且值Value1:

var Array1 = ["apple"];
var Value1 = ["Apple"];
$.each(Array1, function(arrKey,arrVal){
    if(arrVal.toLowerCase() == Value1.toLowerCase() && arrVal !== Value1)
        Array1[arrKey] = Value1;
});
相关文章: