2

I currently have this Object:

schoolsObject = [{
  "college_1":
    {
      "id":"college_1",
      "location":"Victoria",
      "name":"College One"
    },
  "college_2":
    {
      "id":"college_2",
      "location":"Tasmania",
      "name":"College Two"
    }
  }];

I want to remove the top level keys ie. college_1, college_2 and 'flatten' the object out like this, so I have no 'top level' keys:

flatSchoolsObject = 
    [{
      "id":"college_1",
      "location":"Victoria",
      "name":"College One"
    },
    {
      "id":"college_2",
      "location":"Tasmania",
      "name":"College Two"
    }];

Here is my latest attempt, I've made a lot of different try's but have not been documenting them:

// schoolIDs = Object.keys(schoolsObject);
var schools = {};

for(var i=0; i<Object.keys(schoolsObject).length; i++){
  for (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 this one is not what I'm after as it leaves me with Object {0: Object, 1: Object}.

Is what I want to do here possible or am I looking at it the wrong way?

5 Answers 5

5

Given Object:

schoolsObject = [{
    "college_1":{
        "id":"college_1",
        "location":"Victoria",
        "name":"College One"
    },
    "college_2":{
        "id":"college_2",
        "location":"Tasmania",
        "name":"College Two"
    }
}];

Solution:

Object.values(schoolsObject[0]);

Result:

[{
    "id":"college_1",
    "location":"Victoria",
    "name":"College One"
},{
    "id":"college_2",
    "location":"Tasmania",
    "name":"College Two"
}]
Sign up to request clarification or add additional context in comments.

Comments

4

(Codewise) simplest solution could be using a combination of Object.keys() and Array.map():

flatSchoolsObject = Object.keys( schoolsObject[0] )
                          .map( ( key ) => schoolsObject[0][ key ] );

If the schoolsObject array has more entries, the code would have to be slightly adjusted:

let step1 = schoolsObject.map( ( el ) => {
              return Object.keys( schoolsObject[0] )
                           .map( ( key ) => schoolsObject[0][ key ] );
            })
flatSchoolsObject = [].concat.apply( [], step1 );

(the step1 variable is just introduced for readability reasons.)

5 Comments

I'm getting Uncaught TypeError: schoolsObject.map is not a function when attempting this.
@TimDaff: If your schoolsObject is really as shown in the question, the only reason schoolsObject.map wouldn't be a function would be if you were using an obsolete JavaScript engine. Anything vaguely modern (IE9+) has map on arrays, and the schoolsObject in your question is an array.
Apologies I think I may have misrepresented my object. I followed your ES6 example below, but removed [0] from schoolsObject: schoolsObject = Object.keys(schoolsObject[0]).map(key => schoolsObject[0][key]); This worked exactly how I was hoping.
Ok, I also removed [0] from up voted answer and it worked well.
I'm unsure why .map is not working for the "step1" second solution above, but it works fine when using the the first solution above, or other ES2015 solution below. Thank you for your help everyone.
2

You need to concat the result of extracting values from each item in schoolObject

flatSchoolsObject  = [].concat.call(
    schoolsObject.map(function(item) {
       return Object.keys(item).map(function(key) {
          return item[key];
       })
    })    
)

or using Array.prototype.reduce

flatSchoolsObject = schoolsObject.reduce(function(acc, item) {
  return acc.concat(Object.keys(item).map(function(key){
     return item[key]
  })
}, [])

1 Comment

I was trying your solution, and thank you by the way. I think there maybe a small syntax error after the second return (next line) I think it should have two parenthesis. Like this - > return item[key]; })); That was the only way I could get the JS to work when I was putting it into my code.
1

You can use Array#map on the result of Object.keys to do it. Since you have just a single object in the array, we do it like this:

schoolsObject = Object.keys(schoolsObject[0]).map(function(key) {
  return schoolsObject[0][key];
});

Live example:

var schoolsObject = [
  {
  "college_1": {
    "id": "college_1",
    "location": "Victoria",
    "name": "College One"
  },
  "college_2": {
    "id": "college_2",
    "location": "Tasmania",
    "name": "College Two"
  }
}];
schoolsObject = Object.keys(schoolsObject[0]).map(function(key) {
  return schoolsObject[0][key];
});
console.log(schoolsObject);

With ES2015+ you could use an arrow function to make that shorter:

schoolsObject = Object.keys(schoolsObject[0]).map(key => schoolsObject[0][key]);

Comments

0

// Code goes here
var schoolsObject = [{
  "college_1":
    {
      "id":"college_1",
      "location":"Victoria",
      "name":"College One"
    },
  "college_2":
    {
      "id":"college_2",
      "location":"Tasmania",
      "name":"College Two"
    }
  }];
  var result = Object.keys(schoolsObject[0]).map(function(key){
    return schoolsObject[0][key];
  })

console.log(result);

other version

var schoolsObject = [{
  "college_1": {
    "id": "college_1",
    "location": "Victoria",
    "name": "College One"
  },
  "college_2": {
    "id": "college_2",
    "location": "Tasmania",
    "name": "College Two"
  }
}];
var result = [];

for (var property in schoolsObject[0]) {
  if (schoolsObject[0].hasOwnProperty(property)) {
    result.push(schoolsObject[0][property]);
  }
}

console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.