gpt4 book ai didi

javascript - 从 JSON 中删除元素会留下一个未定义的元素

转载 作者:行者123 更新时间:2023-11-28 00:30:25 25 4
gpt4 key购买 nike

我有一个 JSON 对象,我需要循环遍历并删除一些元素。但是,在删除元素后,我最终得到了一个未定义的元素,这给我带来了问题,因为我无法使用这个“新 JSON”(我试图在数据表中使用它)

以下是我目前正在做的事情

    function dTable(presId){
var allregos = '[{"presId": "a09N0000004UbBnIAK","name": "Something","id": "001N000000Mw7knIAB"},{"presId": "a09N0000004UbBnIAK","name": "test catty","id": "001N000000O98IoIAJ"},{"presId": "a09N0000004UbBnIAK","name": "Something","id": "001N000000Mw7knIAB"}]';
var newJson;
var regoValue;
for (var ke in allregos) {
if (allregos.hasOwnProperty(ke)) {
regoValue = allregos[ke].presId;
if(regoValue != presId){
delete allregos[ke];
}else{
//INstead of delete I could maybe create a new JSON by adding the whole node?
//but I am unable to add the node
//newJson = newJson.allregos[ke];
}
}
}

console.log(allregos);
console.log(newJson);

j$('#myRegos').dataTable( {
"data": newJson,
"destroy": true,
"columns": [
{ "title":"Name", "mData": "name", "class": "center" },
]
} );
}

我的控制台日志显示如下内容:

[undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, Object { presId="a09N0000004W3YLIA0", name="name 1", id="001N000000Mw7knIAB"}, Object { presId="a09N0000004W3YLIA0", name="Call Centre", id="001N000000MvDaMIAV"}, Object { presId="a09N0000004W3YLIA0", name="Who Is", id="001N000000MvIiaIAF"}]

有办法摆脱不设防的元素吗?

我想到的另一个解决办法是不删除元素,而是将适当的元素添加到新的 JSON 中,但我无法做到这一点。我正在尝试类似的事情:

newJson = newJson.allregos[ke];

最佳答案

这里我们将 allRegos 作为对象数组,因此更好的使用方法是利用标准,而不使用for (var ke in allregos) 然后 if (allregos.hasOwnProperty(ke))我还通过调用 JSON.parse(allregos)json 字符串 转换为 真实 json 数据下面是增强的dTable函数另请注意,我添加了另一个对象 presId='a09N0000004UbBnIAz' 只是为了看看当我们调用 dTable('a09N0000004UbBnIAK');

function dTable(presId){
allregos = '[{"presId": "a09N0000004UbBnIAK","name": "Something","id": "001N000000Mw7knIAB"}, {"presId": "a09N0000004UbBnIAK","name": "test catty","id": "001N000000O98IoIAJ"}, {"presId": "a09N0000004UbBnIAK","name": "Something","id": "001N000000Mw7knIAB"},{"presId": "a09N0000004UbBnIAz","name": "Something","id": "001N000000Mw7knIAB"}]';
oldJson = allregos;
var regoValue;

allregos = JSON.parse(allregos);
oldJson = JSON.parse(oldJson);
newJson = [];



for( i=0;i<allregos.length;i++){
regoValue = allregos[i].presId;
if(regoValue != presId){
delete allregos[i];
}else{
newJson.push(allregos[i]);
}
}

console.log('allregos before:');
console.log(oldJson);
console.log('allregos after:')
console.log(allregos);
console.log('newJson after:')
console.log(newJson);

}

关于javascript - 从 JSON 中删除元素会留下一个未定义的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29057658/

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