使用flatmap的json API响应代码不工作javascript

sauutmhj  于 2022-12-01  发布在  Java
关注(0)|答案(1)|浏览(110)

问题我尝试从API中的employer属性返回不包含filteredEmployers列表中的任何名称的对象。
我的尝试我有一段替代代码,在我不连接到API时(即从硬编码数据读取),它似乎工作正常,但当我连接到API时,即使我得到以下响应(检索后立即记录),代码也不会执行...

{
    "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"
                    }
                }
            }
        }
    ]
}

我尝试实现的代码如下:

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

所需的响应为:

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

任何关于如何让这个执行的建议,或者这个方法的替代方案都很感激。
先谢了

kpbwa7wx

kpbwa7wx1#

重申我对你的问题的评论:你只需要把台词改一下

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

const people = json.People;

问题中包含的JSON响应是一个对象,Response.json()返回一个解析为JSON文本响应的解析表示的promise,因此为了访问People属性中的数组,只需要json.People。下面是一个基于所示代码和数据的可运行片段:

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

相关问题