1

How can I remove a property from an object if its value is zero?

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

Output should look like this:

var row = [{
  2015: "95163",
  carseries: "Sindelfingen"
},{
  2014: "38954",  
  carseries: "Bremen"
}];
2
  • 1
    Post your code, what have you tried? Commented Sep 6, 2017 at 9:43
  • 2
    1. filter(). 2. Nothing about this is JSON. What you have is simply an array of objects. I amended the title/description/tags to reflect this 3. jQuery is primarily for amending the DOM, so is not needed for changing a data structure. Commented Sep 6, 2017 at 9:44

3 Answers 3

4

You need to use combination of array iterators: map, filter, and reduce.

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))

Sign up to request clarification or add additional context in comments.

Comments

1

This works too :

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
            }
        }
    }

);

1 Comment

I tested the performance jsperf.com/remove-property-array-iterator-vs-loop and your algorithm seem faster than @Yury Tarabanko one, it's easier to understand too.
0

to delete an item from an object you can use CANCEL and you can get the output you want by using two FOR loops =)

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.