如何在JavaScript中从数组返回一个对象[复制]

问题描述 投票:10回答:5

这个问题在这里已有答案:

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

这是我创建的代码;

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

如何修复代码?

javascript arrays loops object
5个回答
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;
}

6
投票

如果ES6是您的选择,ES6引入了实现此目的的新方法:

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

甚至更简陋:

myArray.find(item => item.isAstronaut)

find()是新的迭代器之一,与filter()map()以及其他更容易使用数组。 find()将返回数组中与条件匹配的第一项。 =>或“箭头函数”意味着您不需要显式包含return语句。

Read more about ES6 iterators


3
投票

一个班轮

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

0
投票

您可以使用isAstronaut过滤掉Array.prototype.filter属性等于false的数组元素。我更喜欢filterArray.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);

0
投票

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

其次,您必须检查房产

第三,你必须检查属性的值是宇航员

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;
   }
© www.soinside.com 2019 - 2024. All rights reserved.