How can I remove the parent keys from a javascript Object? -


i have object:

schoolsobject = [{   "college_1":     {       "id":"college_1",       "location":"victoria",       "name":"college one"     },   "college_2":     {       "id":"college_2",       "location":"tasmania",       "name":"college two"     }   }]; 

i want remove top level keys ie. college_1, college_2 , 'flatten' object out this, have no 'top level' keys:

flatschoolsobject =      [{       "id":"college_1",       "location":"victoria",       "name":"college one"     },     {       "id":"college_2",       "location":"tasmania",       "name":"college two"     }]; 

here latest attempt, i've made lot of different try's have not been documenting them:

// schoolids = object.keys(schoolsobject); var schools = {};  for(var i=0; i<object.keys(schoolsobject).length; i++){   (var property in schoolsobject) {     if (schoolsobject.hasownproperty(property)) {       schools[i] = {         'id': schoolsobject[property]['id'],         'name' : schoolsobject[property]['name'],         'location': schoolsobject[property]['location'],       };     }   } } console.log(schools) 

obviously 1 not i'm after leaves me object {0: object, 1: object}.

is want here possible or looking @ wrong way?

(codewise) simplest solution using combination of object.keys() , array.map():

flatschoolsobject = object.keys( schoolsobject[0] )                           .map( ( key ) => schoolsobject[0][ key ] ); 

if schoolsobject array has more entries, code have adjusted:

let step1 = schoolsobject.map( ( el ) => {               return object.keys( schoolsobject[0] )                            .map( ( key ) => schoolsobject[0][ key ] );             }) flatschoolsobject = [].concat.apply( [], step1 ); 

(the step1 variable introduced readability reasons.)


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -