2017-02-26 21 views
3

:)刪除任何其數值大於給定數字的屬性

我需要刪除數值大於給定數字的屬性。我已經看過這個問題:How do I remove a property from a JavaScript object?和這一個:Remove some properties from array of javascript objects和這一個:remove item from array javascript但我仍然無法得到我需要的理想答案。 (他們要麼只返回我不需要數字或陣列中的其他部分)

這是我寫的代碼:

function removeNumbersLargerThan(num, obj) { 
arr = []; 
for (var i = 0; i < obj.length; i++) { 
return arr[i] > 5; 
} 
} 
var obj = { 
    a: 8, 
    b: 2, 
    c: 'montana' 
}; 
removeNumbersLargerThan(5, obj); 

這是我的結果:

console.log(obj); // => { a: 8, b: 2, c: 'montana' } 

正確的console.log應該是這樣的,但:

{ b: 2, c: 'montana' } 

有什麼建議?謝謝! PS:我是新手,即使我試圖遵守規則,我的問題似乎也被大大降低了。如果我發佈的不正確,是否有人可以讓我知道我做錯了,如果他們打算讓我失望?這樣我可以改進。我在這裏學習! :D非常感謝!

回答

4

function removeNumbersLargerThan(num, obj) { 
 
    for (var key in obj) {     // for each key in the object 
 
    if(!isNaN(obj[key]) && obj[key] > num) // if the value of that key is not a NaN (is a number) and if that number is greater than num 
 
     delete obj[key];      // then delete the key-value from the object 
 
    } 
 
} 
 

 
var obj = { 
 
    a: 8, 
 
    b: 2, 
 
    c: 'montana' 
 
}; 
 

 
removeNumbersLargerThan(5, obj); 
 

 
console.log(obj);

+1

可愛的解決方案,upvoted。 –

+1

謝謝您的解答!很有幫助!! :d – learninghowtocode

2

Object.keys()函數返回給定對象的所有keys作爲數組。然後,迭代它們並檢查指定的鍵是否大於給定的數字,如果是 - 刪除它。

var obj = { a: 8, b: 2, c: 'montana', d: 12 }; 
 

 
function clean(obj, num){ 
 
    Object.keys(obj).forEach(v => obj[v] > num ? delete obj[v] : v); 
 
    console.log(obj); 
 
} 
 

 
clean(obj, 5);

+0

大,簡潔的答案刪除對象的屬性,但可能是一個有點可怕的新程序員,可能需要一點解釋。 – Mitch

+0

非常感謝你! – learninghowtocode

+0

@Mitch完成了。 –

2

javascript在問題不檢查對象的屬性值。您可以使用Object.entries()得到屬性鍵,值對,for..of循環數組遍歷屬性和值,如果值等於或大於5

function removeNumbersLargerThan(num, obj) { 
    for (let [key, value] of Object.entries(obj)) { 
    if (typeof value === "number" && value > 5) delete obj[key] 
    } 
}