Egidi
Egidi

Reputation: 1776

How to filter a JSON in nodejs

I have the following JSON stored in a variable named data. How can i filter it excluding the "0" values?

{
  "BTC": "0",
  "XCP": "0",
  "LTC": "0",
  "NXT": "0",
  "XPM": "0",
  "NMC": "0",
  "MMC": "0",
  "NOBL": "0",
  "USDE": "0",
  "SOC": "0",
  "KDC": "0",
  "DOGE": "0.00000001",
  "GLB": "0",
  "Q2C": "0",
  "FOX": "0",
  "MRC": "0",
  "MTS": "0"
}

I tried:

   var datos = data.filter(function(data){
    return !!data;
    });
    res.send(data);

but it's telling me

Object # has no method 'filter'

Regards,

Upvotes: 0

Views: 316

Answers (2)

bits
bits

Reputation: 8340

var dataObj = {
  "BTC": "0",
  "XCP": "0",
  "LTC": "0",
  "NXT": "0",
  "XPM": "0",
  "NMC": "0",
  "MMC": "0",
  "NOBL": "0",
  "USDE": "0",
  "SOC": "0",
  "KDC": "0",
  "DOGE": "0.00000001",
  "GLB": "0",
  "Q2C": "0",
  "FOX": "0",
  "MRC": "0",
  "MTS": "0"
}

var keys = Object.keys(dataObj);
keys.forEach(function(key){ if(dataObj[key] === "0") delete dataObj[key];})

console.log(dataObj);

Upvotes: 1

Geoff448
Geoff448

Reputation: 31

Objects dont have a filter method, you need to convert your object to an array if you want to use the array filter method.

But to answer the question,

var newData = {};

for(i in data){
    if(data.hasOwnProperty(i) && data[i] != "0"){
       newData[i] = data[i];
    }
}

Upvotes: 2

Related Questions