I am getting strange output when using map() on array of objects, how do I fix it?

129 views Asked by At

I am filtering null values from an array of objects but receiving not a clean array as output

//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)

So my goal is to get empty values in array of objects and get their keys. What am I doing wrong here and how do I fix it so that all inputs are return correctly?

3

There are 3 answers

0
John Long On

Flattening the array solved it,

var flatArray = Array.prototype.concat.apply([], input1);

Thanks for the suggestions!!

0
truonghungit On
var emptyKeys = input1.map(function (object) {
    return Object.keys(object).filter(function (key) {
        return object[key] === '';
    });
}).filter(function(item){
 return item.length !== 0;
});

Is that what you mean?

1
Aditya Prasoon On
input1.reduce(function(accumulator, currentValue){
    accumulator.push(...Object.entries(currentValue).filter((kvPair) => kvPair[1] === '').map(ele => ele[0]));
    return accumulator;
}, [])