javascript - jQuery 更改对象数组的任意键的值

标签 javascript jquery arrays key-value

我有一个通过 AJAX 导入的数组。 我想基于原始数组创建一个新数组,并扫描整个新数组,以便清除与其关联的键的值。

导入的数据集如下所示:

[
    {id:"1", color:"red_blue", height:"100_200" },
    {id:"2", color:"green", height:"100_20" },
    {id:"3", color:"orange_yellow", height:"50" }
]

jQuery 流程如下所示

dataSet = JSON.parse(response);

// create a new array based on the imported array
var row = 0;

$.each(dataSet, function(key, value) {
    cleanDataSet.push(dataSet[row]);
    row++;
});

// clean the new array
var row = 0;

// Go through each row of the array
$.each(cleanDataSet, function(key, value) {

    // Go through each key and value of this array
    $.each(cleanDataSet[row], function(key, value) {
        var myVariable = thisValueWhateverTheKey.split('_');

        // if a split is detected in the value
        if (myVariable[1]) {
            // Update the value 
            thisValueWhateverTheKey = myVariable[0];
        }
        row++;
    });
});

console.log(cleanDataSet)

"thisValueWhateverTheKey" 部分显然是我无法弄清楚的部分。 当我定位特定键的值时,这很容易(我会使用“value.nameofmykey”,但当我定位任何键的任何值时,情况就不那么容易了。单独使用“value”是行不通的。

最佳答案

您可以直接使用value,很可能您会因为在两个循环中使用key, value而感到困惑。另请注意,您要按双下划线 __ 进行拆分,根据您的数据,它需要是单个 _

以下是如何简化的方法:

$.each(cleanDataSet, function(index, cleanDataSetRow){  

   // Go through each key and value of this array

    $.each(cleanDataSetRow, function(key, value){ 

        var myVariable = value.split('_');

        // if a split is detected in the value

        if(myVariable[1]){

            // Update the value 
            cleanDataSetRow[key] = myVariable[0];

        }

    });
});

关于javascript - jQuery 更改对象数组的任意键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61086490/

相关文章:

javascript - jquery multitype 锯齿状数组表现奇怪

javascript - 在基于 JSF 1.1 的 Web 应用程序中缩小 js 和 css 的最佳方法

javascript - 即使添加了新问题,提交按钮如何始终位于页面下方

php - jQuery (this) 作为 jQuery Ajax 的继承?

javascript - 在 Javascript/Jquery 中执行 url 而不在浏览器上打开它

javascript - 单击复选框更改字段集类

java - 如何将用户字符串输入与整个数组中的字符串进行比较?

javascript - "bootstrapping"在 Angular 2 的上下文中意味着什么?

javascript - 嵌套 AJAX 和用户事件

java - 如何在 C++ 中最有效地将像素数组渲染到窗口?