如何从JavaScript中的数组返回对象

时间:2018-12-24 17:01:42

标签: javascript arrays loops object

创建一个函数,该函数接受人员对象数组,并从该数组中返回第一个找到的宇航员对象。

这是我创建的代码;

function findFirstAstronaut(people) {
    for (let i = 0; i < people.length; i++) {
        if (people.astronaut[i] === false) {
            return null
        }
        else  if (people.astronaut[i]) {
            return people[i]
        }
    }

我的代码针对此测试运行;

describe("findFirstAstronaut", () => {
  it("returns null if no Astronaut is in the array", () => {
    expect(findFirstAstronaut([])).to.be.null;
  });

  it("returns a person object who is an astronaut", () => {
    const astronaut = { name: "Tim Peake", isAstronaut: true };
     expect(findFirstAstronaut([astronaut])).to.have.keys([
      "name",
      "isAstronaut"
    ]);
    expect(findFirstAstronaut([astronaut]).isAstronaut).to.be.true;
  });

  it("returns the first astronaut from the array", () => {
    const astronauts = [
      { name: "Johnny Karate", isAstronaut: false },
      { name: "Neil Armstrong", isAstronaut: true },
      { name: "Valentina Tereshkova", isAstronaut: true },
      { name: "Bert Macklin", isAstronaut: false },
      { name: "Eileen Collins", isAstronaut: true },
      { name: "Kip Hackman", isAstronaut: false }
    ];
    expect(findFirstAstronaut(astronauts)).to.eql({
      name: "Neil Armstrong",
      isAstronaut: true
    });
  });
});

如何修复我的代码?

5 个答案:

答案 0 :(得分:6)

如果您可以选择ES6,则ES6引入了一种新的方法来实现这一目标:

myArray.find(item => {
  return item.isAstronaut
})

或更缩写:

myArray.find(item => item.isAstronaut)

find()是新的迭代器之一,它与filter()map()以及其他迭代器一起可以更轻松地处理数组。 find()将返回数组中符合条件的第一项。 =>或“箭头功能”意味着您无需显式包括return语句。

Read more about ES6 iterators

答案 1 :(得分:3)

您需要为数组使用索引。

people[i]                // for the object
people[i].isAstronaut    // for a property of the object

然后,您只需要检查isAstronaut是否为true并随物品一起返回即可。

for循环的末尾,返回null,以寻找一名找不到的宇航员。

如果您在循环内进行检查,则返回错误的结果将为时过早。

function findFirstAstronaut(people) {
    for (let i = 0; i < people.length; i++) {
        if (people[i].isAstronaut) {
            return people[i];
        }
    }
    return null;
}

答案 2 :(得分:2)

一支班轮

arr.filter(item => item.isAstronaut)[0]

答案 3 :(得分:0)

您可以使用isAstronaut过滤掉具有Array.prototype.filter属性等于false的数组元素。我不喜欢filter胜过Array.prototype.find,因为并非所有浏览器都支持ES6。

有了过滤后的数组后,只需将元素放在0索引位置即可。如下所示:

const astronauts = [{
    name: "Johnny Karate",
    isAstronaut: false
  },
  {
    name: "Neil Armstrong",
    isAstronaut: true
  },
  {
    name: "Valentina Tereshkova",
    isAstronaut: true
  },
  {
    name: "Bert Macklin",
    isAstronaut: false
  },
  {
    name: "Eileen Collins",
    isAstronaut: true
  },
  {
    name: "Kip Hackman",
    isAstronaut: false
  }
];

//Array destructuring to get the first astronaut:
var [firstAstronautFound] = astronauts.filter(el => el.isAstronaut);

//Line above is same as doing this:
//var firstAstronautFound = astronauts.filter(el => el.isAstronaut)[0];

console.log(firstAstronautFound.name);

答案 4 :(得分:0)

首先,您可能需要检查数组中是否有任何项目,否则返回null。

第二,您必须检查属性

第三,您必须检查属性isAstronaut的值

function findFirstAstronaut(people) {
   if (people.length > 0)
    {
      for (let i = 0; i < people.length; i++) {
         if (("name" in people[i]) && ("isAstronaut" in people[i])) {
           if (people[i].isAstronaut)
              return people[i];              
           else  
              return true;
       }
      }
     }
    else
      return null;
   }