Monday, March 20

Fetching value from nested object, or null ( JavaScript )


Introduction

A simple function which will safely return the value or null from a nested set of objects. With this function it makes it much easier for you to know that you are always either going to get the existing value, or if that object path does not exist, you will get a value of null.






Source Code

Example Data - JavaScript (ES6)

var savedata = { data: { users: { username: { name: 'first last', pass: 'password' }, test: { name: 'test user', pass: '12345' } }, version: '17.03.20' } } ;


Source Code - JavaScript (ES6)

const getVal = ( obj, path ) =>
   path.reduce(
       ( child, prop ) => child && child [prop] ? child [ prop ] : null, obj
   );

console.log( getVal( savedata, [‘data’, ‘users’, ‘username’] ) );
// [ ‘cool’, ‘yup’]

console.log( getVal( savedata, [‘data’, ’user’, ‘bob’] ) );
// null



Source Code - Javascript ( ! ES6 )

function getVal( obj, path ) {
   return path.reduce(
     function ( child, prop) {
       return child && child[ prop ] ? child[ prop ] : null;
     }, obj
   );
};

0 comments :

Post a Comment