我有一个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];
答案 0 :(得分:1)
此处我们将 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);
}
答案 1 :(得分:0)
您可以通过完全覆盖对象来摆脱元素。
说你有
var myObject = {
"keyFoo" : "valueFoo",
"keyBar" : "valueBar",
"keyBaz" : undefined
};
为了找出哪些值未定义,您可以使用您的对象,并仅设置返回true的值。在这种情况下,您可以隔离&#34; keyBaz&#34;,因为 (x.keyBaz)在强制转换为布尔上下文时返回false,而 (x.keyFoo)和(x.KeyBar)在强制转换为布尔上下文时都返回true。您也可以在数组中执行此操作。
然后您可以通过执行以下操作覆盖对象:
myObject = {
"keyFoo" : "valueFoo",
"keyBar" : "valueBar"
};