PlayHardGoPro
PlayHardGoPro

Reputation: 2932

Map through an inner array of an Object

I have this object:

let arr = [{  
    id : 1,
    usr : 'pimba',
    xyz: null
  },
  {
    id  : 2,
    usr : 'aloha',
    xyz: {
     xyz_id: 2      
    }    
  },
  {
    id  : 3,
    age : 'pruu',
    xyz: null
  }];

As you can notice, sometimes xyz is null and sometimes it's not.
I need to recognize whether it is null or not, so I can read it.
I was trying to use map() function but I can't set some sort of filter to only execute the annonymous function when it is NOT null.

I managed to do something like this:

let result = Object.values(arr).map(function(row){
  if(row['xyz'] != null) {
    console.log(row['xyz_id']);
  }
});

what If I want a new array containing ONLY xyz_id ? Is there a shorter version ?

Second case:

There are more than 1 value inside xyz and it's NOT "named".

let arr = [{  
    id : 1,
    usr : 'pimba',
    xyz: null
  },
  {
    id  : 2,
    usr : 'aloha',
    xyz: {
     xyz_id: {"value1Here", "Value2Here"}      
    }    
  },
  {
    id  : 3,
    age : 'pruu',
    xyz: null
  }];

Upvotes: 2

Views: 66

Answers (3)

Ram
Ram

Reputation: 144729

It seems you want to map the array only for the elements that have not-null xyz property. One option is using both .filter and .map methods. Another option is using the .reduce method:

let result = arr.reduce(function(ret, row) {
   // assuming `xyz` can be only `null` or an object
   if ( row.xyz !== null ) {
     ret.push(row.xyz.xyz_id);
   }
   return ret;
}, []); 

Upvotes: 3

ABC
ABC

Reputation: 2148

var a = {one: 1, two: null, three: 3, four: true}
var y = []
let scan = (obj) => { 
  Object.keys(obj).forEach(x => {
    if (obj[x] === null) {
       console.log('Its null')
    } else { 
       // Extend here to datatypes
      y.push(obj[x])
    }
  });
}
scan(a)
console.log(y)

Upvotes: 1

Evan Snapp
Evan Snapp

Reputation: 543

You might want to look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

const notNull = arr.filter(elm => elm.xyz !== null);

Upvotes: 2

Related Questions