2017-09-06 53 views
0

如何從對象中移除屬性(如果其值爲零)?如果值爲0,則從數組中的對象中移除屬性

var row = [{ 
    2013: "0", 
    2014: "0",  
    2015: "95163", 
    carseries: "Sindelfingen" 
},{ 
    2013: "0", 
    2014: "38954", 
    2015: "0", 
    2016: "0", 
    carseries: "Bremen" 
}]; 

輸出應該是這樣的:

var row = [{ 
    2015: "95163", 
    carseries: "Sindelfingen" 
},{ 
    2014: "38954", 
    carseries: "Bremen" 
}]; 
+1

發佈你的代碼,你有什麼試過? –

+2

1. ['filter()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)。 2. *沒有*關於這是JSON。你擁有的只是一組對象。我修改了標題/描述/標籤以反映這一點3. jQuery主要用於修改DOM,因此不需要更改數據結構。 –

回答

2

你需要使用數組迭代器的組合:mapfilterreduce

function clean(obj) { 
 
    return Object.keys(obj) // get own keys 
 
       .filter(function(key) { // keep non '0' values 
 
       return obj[key] !== '0' 
 
       }) 
 
       .reduce(function(out, key) { // recreate object using filtered keys 
 
       out[key] = obj[key] 
 

 
       return out 
 
       }, {}) 
 
} 
 

 
var row = [{ 
 
    2013: "0", 
 
    2014: "0", 
 
    2015: "95163", 
 
    carseries: "Sindelfingen" 
 
}, { 
 
    2013: "0", 
 
    2014: "38954", 
 
    2015: "0", 
 
    2016: "0", 
 
    carseries: "Bremen" 
 
}]; 
 

 
// apply clean function to each element of initial array 
 
console.log(row.map(clean))

1

這工作太:

row.forEach(// loop through your array 
    function(element) { 
     for (key in element) { // for every key in the current object 
      if (element[key] === '0') { // if it's valued to '0' 
       delete element[key]; // remove it from the object 
      } 
     } 
    } 

); 
+0

我測試了性能https://jsperf.com/remove-property-array-iterator-vs-loop,並且你的算法似乎比@Yury Tarabanko更快,這也更容易理解。 – Nolyurn

0

從對象中刪除的項目,您可以使用取消,您可以通過使用兩個for循環得到你想要的輸出=)

var row = [{ 
 
    2013: "0", 
 
    2014: "0",  
 
    2015: "95163", 
 
    carseries: "Sindelfingen" 
 
},{ 
 
    2013: "0", 
 
    2014: "38954", 
 
    2015: "0", 
 
    2016: "0", 
 
    carseries: "Bremen" 
 
}]; 
 

 
for(var i = 0; row[i]; i++){ 
 
    for(var key in row[i]) { 
 
    if(row[i][key] === "0") delete row[i][key]; 
 
    } 
 
} 
 

 
console.log(row);

相關問題