如果value为0,则从数组中的对象中删除属性

时间:2017-09-06 09:42:29

标签: javascript jquery

如果对象的值为零,如何从对象中删除属性?

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"
}];

3 个答案:

答案 0 :(得分: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 :(得分: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
            }
        }
    }

);

答案 2 :(得分:0)

从可以使用CANCEL的对象中删除项目,您可以使用两个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);