如何从 JavaScript 中的数组返回对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53915995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return an object from an array in JavaScript
提问by Geo
Create a function that takes an array of people objects and returns the first found astronaut object from the array.
创建一个函数,该函数接受一组人对象并从该数组中返回第一个找到的宇航员对象。
This is the code that I have created;
这是我创建的代码;
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]
}
}
My code is run against this test;
我的代码是针对这个测试运行的;
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
});
});
});
How do I fix my code?
如何修复我的代码?
采纳答案by Nina Scholz
You need to use the index for the array.
您需要使用数组的索引。
people[i] // for the object people[i].isAstronaut // for a property of the object
people[i] // for the object people[i].isAstronaut // for a property of the object
Then you need only a check if isAstronautis trueand return with the item.
然后您只需要检查是否isAstronaut是true并返回该项目。
At the end outside of the forloop, return null, for a not found astronaut.
在for循环外的最后null,为未找到的宇航员return 。
If you check inside the loop, you will return too early with the wrong result.
如果您在循环内部检查,您将过早返回错误结果。
function findFirstAstronaut(people) {
for (let i = 0; i < people.length; i++) {
if (people[i].isAstronaut) {
return people[i];
}
}
return null;
}
回答by Toby
ES6 introduces a new way to achieve this, if ES6 is an option for you:
ES6 引入了一种新方法来实现这一点,如果 ES6 是您的一个选择:
myArray.find(item => {
return item.isAstronaut
})
Or even more abbreviated:
或者更简写:
myArray.find(item => item.isAstronaut)
find()is a one of the new iterators, along with filter()and map()and others for more easily working with arrays. find()will return the first item in your array that matches the condition. The =>or "arrow function" means that you do not need to explicitly include the return statement.
find()是新的迭代器的一个,连同filter()与map()和其他与阵列更容易的工作。find()将返回数组中与条件匹配的第一项。的=>或“箭功能”的意思是,你并不需要明确包括return语句。
回答by ellipsis
One liner
一个班轮
arr.filter(item => item.isAstronaut)[0]
回答by Tom O.
You could simply filter out array elements that have an isAstronautproperty equal to false using Array.prototype.filter. I prefer filterto Array.prototype.findsince ES6 isn't supported in every browser.
您可以简单地使用 过滤掉isAstronaut属性等于 false 的数组元素Array.prototype.filter。我更喜欢ES6 filter,Array.prototype.find因为并非每个浏览器都支持 ES6。
Once you have the filtered array simply take the element in the 0index position. Something like below:
获得过滤后的数组后,只需将元素置于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);
回答by Sonal Borkar
First, you may need to check whether there is any item in array or else return null.
首先,您可能需要检查数组中是否有任何项目,否则返回 null。
Second, you have to check for the property
其次,你必须检查财产
Third, you have to check for the value of the property isAstronaut
第三,你必须检查属性 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;
}

