如何遍历包含对象的数组并进行比较

How to loop through an array containing objects and do comparison

我正在使用 ionic 4。我从 API 得到结果然后得到这样的结果显示

[
 {"name":John,"age":20},
 {"name":Peter,"age":35},
 {"name":Alex,"age":15}
]

但是我想获取名字只是为了检查是否与我的条件重名。但是我不能直接从 API 中得到结果,我需要硬编码来做比较。这是我的代码:

 this.http.get(SERVER_URL).subscribe((res) => {
      const data = [
        { name: John, age: 21 },
        { name: Thomas, age: 25 },
    ];

      const ppl= data.find(people=> people.name === 'alex');
      console.log(ppl);
  });

所以,我的第一个问题 是如何直接从API 中获取名称,而不像现在我对API 中的结果进行硬编码。我的 第二个问题 是当我进行比较时,我想显示结果 'already exist' 或 'can use this name'。因为如果我这样写代码,我会得到错误 Type 'void' is not assignable to type 'boolean':

const ppl= data.find((people)=> {
 if(people.name === 'alex') {
   this.text = 'already exist'
  } else {
  this.text = 'can use this name'
  }});
  console.log(ppl);

谁能帮帮我?非常感谢

不定义数据,而是使用响应的内容; res 将具有您在 data 中声明的完全相同的内容。

this.http.get(SERVER_URL).subscribe(res => {

  // If successful, res is an array with user data like the following
  // [
  //   {name: "John", age: 21},
  //   {name: "Thomas", age: 25},
  //   ...
  // ]

  if (res.find(user => user.name === 'alex')) {
    console.log ('Username has been taken');
  } else {
    console.log('Username is available');
  }

});

取自 MDN docs on Array.prototype.find():

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

那样的话

res.find(user => user.name === 'alex')

将return一个用户对象如果任何用户名匹配alex,或者undefined如果none 的 user.name 属性匹配 alex

undefined 的计算结果为 false 用户对象 在条件条件中的计算结果为 true

请记住,您正在将字符串与 === 进行比较,因此,例如,如果您想研究比较字符串的其他方法,Alex 将不会匹配 alex , 看看 this question.

您可能还想处理错误,如何处理它们取决于您,这将取决于响应,但您可以像这样在订阅中访问 error

this.http.get(SERVER_URL).subscribe(res => {

  if (res.find(user => user.name === 'alex')) {
    console.log ('Username has been taken');
  } else {
    console.log('Username is available');
  }

}, error => {

  console.log(error);

}, () => {
  // There is also a 'complete' handler that triggers in both cases
});

编辑。 API returns Object 不是 array

如果您的 API return 是 Object 而不是问题中的 array,您仍然可以迭代属性

this.http.get(SERVER_URL).subscribe(res => {

  // If successful, res is an array with user data like the following
  // {
  //   key1: {name: "John", age: 21},
  //   key2: {name: "Thomas", age: 25},
  //   ...
  // }

  let match = false;

  Object.keys(res).forEach(key => {

    if (res[key].name === 'alex') {
      match = true;
    }

  });

  if (match) {
    console.log ('Username has been taken');
  } else {
    console.log('Username is available');
  }

});

而不是 Object.keys() you could use Object.values() 来获取包含 用户对象的数组 ,然后像以前一样使用 find(),但这似乎效率较低,如下所示:

if (Object.values(res).find(user => user.name === 'alex')) {
    console.log ('Username has been taken');
  } else {
    console.log('Username is available');
}