我有一个通过 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/