在下面的代码段中,return(res)
之前,我记录了它,而不是undefined
但不知何故,它被归还为undefined
。
我做错了什么?
filterData = (inputData, searchedKey) => {
inputData.forEach((data, index) => {
if(data){
if(data.hasOwnProperty(searchedKey)){
const res = data[searchedKey]
console.log(res) /// logs the results
return(res) /// returns undefined
}
var dataToProcess = [];
var fieldKeys = Object.keys(data)
fieldKeys = fieldKeys.filter((field, index) => !field.includes("#"))
fieldKeys.forEach((key, index) => {
dataToProcess.push(data[key]);
})
this.filterData(dataToProcess, searchedKey)
}
})
}
console.log(this.filterData([{"#name": "foo", "#type": "bar"}], "#type"))

答案 0 :(得分:1)
一些问题:
forEach
除了undefined
之外不返回任何其他内容,因此在其回调函数中返回一个值并没有做任何有用的事。if (data)
不足以确保data
是一个对象。例如,对于非零数字也是如此。请改用Object(data) === data
。filter
方法也返回一个数组。所以它符合这一点。以下是如何使其发挥作用:
var filterData = (inputData, searchedKey) => {
inputData = inputData.filter( data => Object(data) === data );
return !inputData.length ? [] :
inputData.filter( data => data.hasOwnProperty(searchedKey) )
.map( data => data[searchedKey] )
// Add the results from recursion:
.concat(filterData([].concat(...
inputData.map( data =>
Object.keys(data)
.filter( key => !key.startsWith("#") )
.map( key => data[key] )
)
), searchedKey));
};
var data = [{
"#name": "foo",
"#title": "mr",
"deeper": [{
"#nope": "bad",
"deepest": [{
"nothing_here": null,
"#type": "deeper bar",
}]
}, {
"#type": "bar",
}]
}];
console.log(filterData(data, "#type"));

如果您只需要第一场比赛,请使用此变体:
var filterData = (inputData, searchedKey) => {
inputData = inputData.filter( data => Object(data) === data );
var res = inputData.find( data => data.hasOwnProperty(searchedKey) );
return res !== undefined ? res[searchedKey] :
// Try in nested objects:
filterData([].concat(...
inputData.map( data =>
Object.keys(data)
.filter( key => !key.startsWith("#") )
.map( key => data[key] )
)
), searchedKey);
};
var data = [{
"#name": "foo",
"#title": "mr",
"deeper": [{
"#nope": "bad",
"deepest": [{
"nothing_here": null,
"#type": "deeper bar",
}]
}, {
"#type": "bar",
}]
}];
console.log(filterData(data, "#type"));

答案 1 :(得分:0)
这是你想要达到的目标吗?
filterData = (inputData, searchedKey) => {
return inputData.map((data, index) => {
if(data){
if(data.hasOwnProperty(searchedKey)){
const res = data[searchedKey]
console.log(res) /// logs the results
return(res) /// returns undefined
}
var dataToProcess = [];
var fieldKeys = Object.keys(data)
fieldKeys = fieldKeys.filter((field, index) => !field.includes("#"))
fieldKeys.forEach((key, index) => {
dataToProcess.push(data[key]);
})
this.filterData(dataToProcess, searchedKey)
}
})
}
console.log(this.filterData([{"#name": "foo", "#type": "bar"}], "#type"))
使用Array#map()
,在很多情况下它非常有用。