Kalimantan Kalimantan - 1 month ago 7
Javascript Question

Filter values from Arrays in Json (JavaScript)

So I have loaded a JSON object from D3 and now want to filter out some columns from the array. My only problem is that doing:

Object.attribute;


doesn't return what I want. The structure of my JSON object is as follows. It holds 1000 objects and each array hold attributes inside of it. I am getting my data from https://data.raleighnc.gov/resource/xce4-kemu.json, for reference.

If I do

Object[0].attribute;


It returns the actual value of the object, so like "12". Where as I want it to return all the values where that key is present

In the URL you can see an example of the JSON. I want to, for example return a JSON where only the issueddate_mth, statelicnum, and constcompletedofficial attributes are present.

An Snippet of what I tried is:

var raleigh_data = "https://data.raleighnc.gov/resource/xce4-kemu.json";
d3.json(raleigh_data, function(error, data) {
var filtered_data = data.filter(function(d,i,e) {
return d.issueddate_mth;
});


}

Answer
var data = [your array of 1000 objects]
var filteredData = [];
data.forEach(function(item) { 
    if (item.issueddate_mth && item.statelicnum && item.constcompletedofficial) {
        filteredData.push(item);
    }
});

This will get you an array that only contains items from your original array with the specified properties.

Also, I am not 100% sure if you only want those three properities. If so, you could easily just push { issueddate_mth: item.issueddate_mth, statelicnum: item.statelicnum, constcompletedofficial: item.constcompletedofficial } instead of item in the forEach callback