json 当遍历嵌套对象并使用match在javascript中给出过滤对象结果时,它返回[object]、[object]等数组

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

上下文我正在使用:Windows 11、VSCode和节点版本18.12.1

我正在编写的代码尝试遍历几个JSON对象。然后,使用数组变量,代码需要过滤每个对象中的某些属性,因为每个对象中的每个name属性中需要过滤的值不止一个。

Question下面的代码可以遍历所有对象的所有级别,并记录该人的姓名、城市和雇主。它还需要过滤掉所有与filteredNames数组中的一个或多个姓名匹配的对象,然后返回所有不包含这些姓名的对象。

下面是工作的代码(如上所述):

let data = [{
    "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"
            }
        }
    }
}
]}]

data.filter(item => {
    iterateObject(item);
});

function iterateObject(obj) {
    for(prop in obj) {
        if(typeof(obj[prop]) == "object"){
            iterateObject(obj[prop]);
        } else {
            if(prop == "name" || prop == "city" || prop == "employer") {
            console.log(prop.toUpperCase() + ': ', obj[prop]);
            }
            //some code goes here which if either of filteredEmployers is in 'employer', nesting position agnostic, i.e. the attribute could be nested deeper or shallower in the object, 
            //then print out all objects which don't contain any of the attributes in filteredEmployers array
        }
    }
}

结果为:

NAME:  TJ
EMPLOYER:  amazon
CITY:  Boston
NAME:  Dominique
EMPLOYER:  IBM
CITY:  Seattle
NAME:  Enrique
EMPLOYER:  Bellkrieg Megasystems
CITY:  New York City
NAME:  Bob
EMPLOYER:  Megasystems
CITY:  Austin

使用一个数组变量,它需要在每个对象的雇主属性中以数组的形式过滤'Megasystems'和'Bellkrieg',因为需要过滤的值不止一个。这也将使它更具适应性,因此在需要时添加到filteredEmployers中相对容易...

我尝试过的方法我针对遇到的问题搜索了各种其他解决方案,但它们似乎无法满足需要...

这是我目前拥有的...

//data of nested objects goes here

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

data.filter(item => {
    iterateObject(item);
});

function iterateObject(obj) {
    for(prop in obj) {
        if(typeof(obj[prop]) == "object"){
            iterateObject(obj[prop]);
        } else {
                            
                checkPeople = Object.values(data).filter(({employer}) =>
    !filteredEmployers.some(filtered => employer?.match(filtered)));
                if(checkPeople !== null) {
            console.log(checkPeople);}
            }
        }
    }
}

但是,它给出了以下内容:

[
      {
        Pagination: {
          NumberOfPeople: 185,
          PageSize: 200,
          PageNumber: 1,
          NumberOfPages: 1
        },
        People: [ [Object], [Object], [Object], [Object] ]
      }
    ]
    [
      {
        Pagination: {
          NumberOfPeople: 185,
          PageSize: 200,
          PageNumber: 1,
          NumberOfPages: 1
        },
        People: [ [Object], [Object], [Object], [Object] ]
      }
    ]
    [
      {
        Pagination: {
          NumberOfPeople: 185,
          PageSize: 200,
          PageNumber: 1,
          NumberOfPages: 1
        },
        People: [ [Object], [Object], [Object], [Object] ]
      }
    ]
    [
      {
        Pagination: {
          NumberOfPeople: 185,
          PageSize: 200,
          PageNumber: 1,
          NumberOfPages: 1
        },
        People: [ [Object], [Object], [Object], [Object] ]
      }
    ] // etc etc 30 times

不应返回分页,People对象应返回不在filteredEmployers列表中的People的所有属性,而不是People: [ [Object], [Object], [Object], [Object]
我所追求的结果如下(或者非常相似):

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

任何建议都很感谢。提前感谢

ovfsdjhp

ovfsdjhp1#

我将您的问题解释为您希望生成一个“People”对象数组,但过滤掉嵌套的“employer”属性是一个字符串(该字符串包含的子字符串是过滤器列表中的一个子字符串)的对象。
如果这是正确的,您可以这样做:

function transform (array, employerFilterList) {
  const people = array.flatMap(o => o.People);
  return people.filter(person => {
    const employer = person?.organization?.company?.employer;

    // If the person has no employer field,
    // then the restricted employer filter doesn't apply,
    // so include the person:
    if (typeof employer !== 'string') return true;

    // Else...
    const employerIsNotFiltered = employerFilterList.every(
      str => !employer.includes(str)
    );

    return employerIsNotFiltered;
  });
}

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"}}}}]}]`;
const data = JSON.parse(json);

const filteredEmployers = ['Megasystems', 'Bellkrieg'];
const result = transform(data, filteredEmployers);

console.log(result); // [{name: "TJ", ...}, {name: "Dominique", ...}]

参考文献:

相关问题