Home > Net >  json API response code using flatmap not working javascript
json API response code using flatmap not working javascript

Time:12-01

Problem I’m trying to return only the objects that don’t contain any of the names on the filteredEmployers list, against the employer attribute, from an API I'm retrieving the data from.

What I've tried I have an alternative piece of code that seems to work fine when I don’t connect to the API (i.e. reading from hardcoded data), but when I connect to the API, even though I get the following response (when immediately logged after retrieval), the code then doesn’t execute…

{
    "Pagination": {
        "NumberOfPeople": 185,
        "PageSize": 200,
        "PageNumber": 1,
        "NumberOfPages": 1
    },
    "People": [
        {
            "name": "TJ",
            "job": "Software Engineer",
            "organization": {
                "company": {
                    "employer": "amazon",
                    "department": "IT"
                }
            },
            "location": {
                "city": "Boston",
                "state": "Massachusetts"
            }
        },
        {
            "name": "Dominique",
            "job": "CEO",
            "organization": {
                "company": {
                    "employer": "IBM",
                    "department": "IT"
                }
            },
            "city": "Seattle",
            "state": "Washington"
        },
        {
            "name": "Enrique",
            "job": "Engineer",
            "organization": {
                "company": {
                    "employer": "Bellkrieg Megasystems",
                    "department": "Construction"
                }
            },
            "location": {
                "address": {
                    "state": "New York",
                    "city": "New York City",
                    "zip": "11323"
                }
            }
        },
        {
            "name": "Bob",
            "job": "Project Manager",
            "organization": {
                "company": {
                    "employer": "Megasystems",
                    "department": "R&D"
                }
            },
            "address": {
                "location": {
                    "quadrant": {
                        "block": 1,
                        "state": "Texas",
                        "city": "Austin"
                    }
                }
            }
        }
    ]
}

The code I’m trying to implement is here:

// constants and variables are defined here, including API credentials and the filteredEmployers array
//FYI const filteredEmployers = ['Megasystems', 'Bellkrieg'];
//the code then fetches the API data is here
.then((response) => {
    return response.json();
})
.then((json) => {
    //console.log(typeof json);
    //console.log(json);
    const people = Array.from(json).flatMap(o => o.People);
    return people.filter(person => {
        const employer = person?.organization?.company?.employer;

        if (typeof employer !== 'string') return true;
        const employerIsNotFiltered = filteredEmployers.every(
            str => !employer.includes(str)
        );
        console.log("This is the outputted data: "   employerIsNotFiltered);
        return employerIsNotFiltered;
    });
})

The desired response is:

[
  {
    name: 'TJ',
    job: 'Software Engineer',
    organization: { company: [Object] },
    location: { city: 'Boston', state: 'Massachusetts' }
  },
  {
    name: 'Dominique',
    job: 'CEO',
    organization: { company: [Object] },
    city: 'Seattle',
    state: 'Washington'
  }
]

Any recommendations on how to get this to execute, or alternatives to this method appreciated.

Thanks in advance

CodePudding user response:

Reiterating my comment on your question: You just need to change the line

const people = Array.from(json).flatMap(o => o.People);

to

const people = json.People;

The JSON response that you included in the question is an object, and Response.json() returns a promise which resolves to an already parsed representation of the JSON text response, so in order to access the array at the People property, you only need json.People. Here is a runnable snippet based on the code and data that you showed:

// The JSON data, copied and pasted from the first code block of your question:
const json = `{"Pagination":{"NumberOfPeople":185,"PageSize":200,"PageNumber":1,"NumberOfPages":1},"People":[{"name":"TJ","job":"Software Engineer","organization":{"company":{"employer":"amazon","department":"IT"}},"location":{"city":"Boston","state":"Massachusetts"}},{"name":"Dominique","job":"CEO","organization":{"company":{"employer":"IBM","department":"IT"}},"city":"Seattle","state":"Washington"},{"name":"Enrique","job":"Engineer","organization":{"company":{"employer":"Bellkrieg Megasystems","department":"Construction"}},"location":{"address":{"state":"New York","city":"New York City","zip":"11323"}}},{"name":"Bob","job":"Project Manager","organization":{"company":{"employer":"Megasystems","department":"R&D"}},"address":{"location":{"quadrant":{"block":1,"state":"Texas","city":"Austin"}}}}]}`;

function mockFetch () {
  return Promise.resolve({
    json: () => Promise.resolve(JSON.parse(json)),
  });
}

const filteredEmployers = ['Megasystems', 'Bellkrieg'];

mockFetch()
  .then(response => response.json())
  .then(json => {
    // Change this line:
    // const people = Array.from(json).flatMap(o => o.People);

    // To:
    const people = json.People;

    return people.filter(person => {
      const employer = person?.organization?.company?.employer;

      if (typeof employer !== 'string') return true;
      const employerIsNotFiltered = filteredEmployers.every(
        str => !employer.includes(str)
      );

      return employerIsNotFiltered;
    });
  })
  .then(console.log);

  • Related