我正在从对象数组中筛选空值,但没有接收到干净的数组作为输出
//returns ,cat,snake,dog,cat,snake
//var input1 = [{"dog":"35","cat":"21","girrafe":"33","snake":"44"},{"dog":"22","cat":"","girrafe":"2","snake":""},{"dog":"","cat":"","girrafe":"88","snake":""}];
//returns ",,dog,girrafe,snake"
//var input1 = [{"dog":"43","cat":"32","girrafe":"1","snake":"33"},{"dog":"1","cat":"23","girrafe":"1","snake":"23"},{"dog":"","cat":"5","girrafe":"","snake":""}];
//returns dog,,dog,cat,snake
//var input1 = [{"dog":"","cat":"s","girrafe":"1","snake":"54"},{"dog":"x","cat":"y","girrafe":"45","snake":"x"},{"dog":"","cat":"","girrafe":"1","snake":""}];
//tried to fix with .join() but then
//returns doggirrafecat,girrafe if I uses console.log(input1.join())
var input1 = [{"dog":"","cat":"s","girrafe":"1","snake":"54"},{"dog":"x","cat":"y","girrafe":"","snake":"x"},{"dog":"s","cat":"","girrafe":"","snake":"ss"}];
//returns typeof object
var emptyKeys = input1.map(function (object) {
return Object.keys(object).filter(function (key) {
return object[key] === '';
});
});
console.log(emptyKeys)
所以我的目标是在对象数组中获取空值并获取它们的键。我在这里做错了什么?我该如何修复它,以便正确返回所有输入?
扁平化阵列解决了这个问题,
var flatArray = Array.prototype.concat.apply([], input1);
谢谢你的建议!!
var emptyKeys = input1.map(function (object) {
return Object.keys(object).filter(function (key) {
return object[key] === '';
});
}).filter(function(item){
return item.length !== 0;
});
你是这个意思吗?
input1.reduce(function(accumulator, currentValue){
accumulator.push(...Object.entries(currentValue).filter((kvPair) => kvPair[1] === '').map(ele => ele[0]));
return accumulator;
}, [])