在Angular中搜索嵌套对象

时间:2018-09-24 12:38:12

标签: javascript arrays angular angular-reactive-forms angular-forms

我在Angular应用中搜索嵌套数组时遇到问题。我必须访问package.name。请帮助谢谢enenfoiewfhfofhfowfoewhfowfoewhfwefwfhowefweofhew8ofwofhewofw8eofhwf

JSON

[{
    "id": 1,
    "name": "Yeah",
    "package_id": 1,
    "price": 100,
    "package": {
        "id": 1,
        "name": "Yeah"
    }
}]

TS

search(event) {
    const val = event.target.value.toLowerCase();

    if (!val) {
        this.users = this.tempUsers;
    }

    const temp = this.tempUsers.filter((row) => {
        return Object.keys(row).some((property) => {
            return row[property] === null ? null : row[property].toString().toLowerCase().indexOf(val) !== -1;
        });
    });

    this.users = temp;
}
  

TS

 getAllUsers() {
    this.usersService.getAll()
      .subscribe(
        (data: any) => {
          console.log(data);
          this.users = data.Users;
          this.tempUsers= [...this.users];
        },
        error => {
          console.log(error);
        });
  }

2 个答案:

答案 0 :(得分:0)

根据您的数据,您可以使用以下过滤器;

const filteredData = data.filter((item) => item.price.toString() === val || item.package_id.toString() === val || item.package.name.toString().toLowerCase().indexOf(val) !== -1 );

//用代码更新

search(event) {
    const val = event.target.value.toLowerCase();
   const filteredData = this.users.filter((item) => item.price.toString() === val || 
   item.package_id.toString() === val || 
    item.package.name.toString().toLowerCase().indexOf(val) !== -1 );

    this.users = filteredData ;
}

答案 1 :(得分:0)

这对您有用吗

const temp = this.tempUsers.filter((row) => {
  return Object.keys(row).some((property) => {
    if (property === 'package') {
      // check package.name value here
      // like return row[property].name === 'something' ? true : false;
    } else {
    // the rest of the outer properties can be checked here
    // not modifying your code here, but make sure it works for you
    return row[property] === null ? null : row[property].toString().toLowerCase().indexOf(val) !== -1;
    }
  });
});

我只回答了有关如何访问array方法内的嵌套对象的问题。希望它对您有所帮助或为您提供一个微调解决方案的想法。