Click here to Skip to main content
15,882,464 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I stacked since 15 days in a simple function in JavaScript but I can not find the solution!

The problem is this: I have to read a json file, and filter the result... and if zip not available then return 'false'

my example json data

JavaScript
{"110003":{"Districtname":"SOUTH EAST DELHI","StateName":"DELHI"},"110014":{"Districtname":"SOUTH EAST DELHI","StateName":"DELHI"},"110020":{"Districtname":"SOUTH EAST DELHI","StateName":"DELHI"},"110025":{"Districtname":"SOUTH EAST DELHI","StateName":"DELHI"},"110036":{"Districtname":"NORTH DELHI","StateName":"DELHI"},"110039":{"Districtname":"NORTH DELHI","StateName":"DELHI"},"110040":{"Districtname":"NORTH WEST DELHI","StateName":"DELHI"},"110042":{"Districtname":"NORTH DELHI","StateName":"DELHI"},"110044":{"Districtname":"SOUTH EAST DELHI","StateName":"DELHI"}}


What I have tried:

function filterzip(zip) 
{
    let rawdata = fs.readFileSync('zip.json');
    var mydata = JSON.parse(rawdata);
    console.log("parse:"+ mydata);
    const value = zip;
    const result = mydata.filter(zip);
    console.log("result: " + result);
    if(result == 'undefined')
    {
        return(false);
    }
    else
    {
        return(true);
    }
};
Posted
Updated 8-Nov-22 23:23pm
Comments
Richard MacCutchan 9-Nov-22 4:10am    
What is the problem?

1 solution

You haven't explained what the problem is. Based on what you have shown us, you have several problems.

1) The JSON you've shown is an object, but you are trying to call the Array.prototype.filter[^] method on it. That method only works for arrays, not objects.

2) You're passing a string value to the filter function, when that function expects a callback which will be called on every element of the array. If your source actually was an array, you'd want to call Array.prototype.includes[^] instead. But that won't work with the source you've shown, which is a single object.

3) The result of the filter function will be a new array with the matching elements from the source array. The result of the includes function will be true or false. Neither of those values will be equal to the string 'undefined'.

Since your source data appears to be an object, try using the Object.prototype.hasOwnProperty[^] function instead:
JavaScript
function filterzip(zip) 
{
    const rawdata = fs.readFileSync('zip.json');
    const mydata = JSON.parse(rawdata);
    console.log("parse:", mydata);
    return mydata.hasOwnProperty(zip);
};
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900