我试图从对象数组内的嵌套数组中获得特定字段值。我假设我会使用map,但每次我这样使用它,我都会得到两个空数组嵌套在两个空对象中。我知道这是错的,我只是在展示我的思维过程。
function getChildArray(item, index) {
var x = [item.hobbies]
return x
}
console.log(parentArray.map(getChildArray))
这是我的文档结构的一个例子:
[
{
"id":12345678900,
"name":"Jasmin",
"age":27,
"hobbies":[
{
"id":1221,
"name":"hiking",
"when":"anytime"
},
{
"id":9865,
"name":"eating",
"when":"all the time"
}
]
},
{
"id":223456789001,
"name":"Joe",
"age":35,
"hobbies":[
{
"id":989,
"name":"gaming",
"when":"anytime"
},
{
"id":2355,
"name":"online gaming",
"when":"all the time"
}
]
}
]
例如,我如何能够仅通过名字检索Joe的爱好列表?
var joe = parentArray.find(function (item) {
return item.name === 'Joe';
});
if (joe) {
var joesHobbiesNames = joe.hobbies.map(function (hobbie) {
return hobbie.name;
});
}
或者在ES6中
var joe = parentArray.find((item) => item.name === 'Joe');
if (joe) {
var joesHobbiesNames = joe.hobbies.map((hobbie) => hobbie.name);
}
由于array.find
尚未在所有浏览器中可用,并且您可能没有使用构建工具,因此这里有一个完整的ES5方法。使用filter
和map
:
var data = [{ id: 12345678900, name: 'Jasmin', age: 27, hobbies: [{'id': 1221, 'name': 'hiking', 'when': 'anytime'}, { 'id': 9865, 'name': 'eating', 'when': 'all the time' }] }, { id: 223456789001, name: 'Joe', age: 35, hobbies: [{'id': 989, 'name':
'gaming', 'when': 'anytime'}, { 'id': 2355, 'name': 'online gaming', 'when': 'all the time' }]}];
function getHobbiesByName(name) {
return data.filter(function(person) {
return (person.name == name);
})[0].hobbies.map(function(hobby) {
return hobby.name
})
}
console.log(getHobbiesByName('Joe'))
一个快速返回具有所需属性和该属性值的项的函数:
data = [{id:1,name:'Bob',hobbies:['a','b']},{id:2,name:'Alice',hobbies:['c','d']}];
function getPerson(property,value){
for(var i=0;i<data.length;i++) if(data[i][property] == value) return data[i];
return {};
}
和一个测试:
console.log(getPerson('name','Bob'));
console.log(getPerson('name','Bob').hobbies);