简体   繁体   English

循环中的Javascript对象属性不会删除

[英]Javascript object properties in loop not deleting

I'm having trouble understanding the behavior of this javascript code. 我在理解此javascript代码的行为时遇到了麻烦。

const devices = searchResult.results.forEach(device => {
    const temp = Object.keys(device.fields);

    for(var property in temp) {
        if(device.fields.hasOwnProperty(property)) {
            if (!usedPropertiesAcrossModels.has(property)) {
                delete device.fields[property];
            }
        }
    }
}

I am trying to delete the keys if a javascript object that do not belong to a set. 我正在尝试删除不属于集合的javascript对象的键。 I have stepped through the debugger, and I know that there is only one element in the set and 15 elements in device.fields . 我已逐步调试该调试器,并且知道该集中只有一个元素,而device.fields只有15个元素。 No matter what, nothing is being deleted from device.fields , I have no idea why. 不管怎样,从device.fields什么也没有删除,我也不知道为什么。 Moreover, temp seems to be undefined until I am out of the loop. 而且,直到我退出循环, temp似乎才是不确定的。 Property is always undefined even though there are items in temp! 即使临时有项目, Property也始终是未定义的! This doesn't make any sense. 这没有任何意义。

 searchResult = {}; searchResult.results = [{ fields:{ name: 'hello', type:'gekko', random:'randomString' } } ] usedPropertiesAcrossModels = { name: 'hello', random:'hello' } const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields).map((property)=>{ if(device.fields.hasOwnProperty(property)) { if (!usedPropertiesAcrossModels.hasOwnProperty(property)) { delete device.fields[property]; } } }) }) console.log(searchResult) 

Using map fixed the issue as in your case the for in was giving index instead of the keys of the object.Or as martin said you can consider using for of as well. 使用map可以解决问题,例如for in提供索引而不是对象的键。或者如马丁所说,您也可以考虑使用for of。

const temp = Object.keys(o) will give you array of object's keys. const temp = Object.keys(o)将为您提供对象键的数组。 You should use for of loop instead of for in , as you need to iterate through values of it, not their keys in temp object: 您应该使用for of循环而不是for in ,因为您需要遍历循环的值,而不是遍历temp对象中的键:

 const o = { a: 1, b: 2, c: 3 }; const temp = Object.keys(o); console.log(temp); // this will iterate through `temp` keys, so 0, 1, 2 for (const property in temp) { console.log('wrong:', property); } // this will iterate through `temp` values, so 'a', 'b', 'c' for (const property of temp) { console.log('correct:', property); } // or you could iterate via `forEach()` temp.forEach(property => { console.log('correct:', property); }); 

Also with for of loop, you do not need the hasOwnProperty check. 同样, for of循环,您不需要hasOwnProperty检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM