Skip to content

Instantly share code, notes, and snippets.

@alioguzhan
Last active December 24, 2015 02:29
Show Gist options
  • Save alioguzhan/6730668 to your computer and use it in GitHub Desktop.
Save alioguzhan/6730668 to your computer and use it in GitHub Desktop.
convert an 'array' which includes multiple (different) objects as element into 'one object'.
var toObject = function(obj){
var newObj = {};
for(var i = 0; i<obj.length; i++){
for(var k in obj[i]){
if(obj[i].hasOwnProperty(k)) {
newObj[k] = obj[i][k];
}
}
}
return newObj;
};
// Example usage
var someThing = [
{'john': 19},
{'marry': 22},
{'ali': 22},
{'car': 'sold'}
];
toObject(someThing);
// Output
[object Object] {
ali: 22,
car: "sold",
john: 19,
marry: 22
}
// ----------------------------------------------------------
// if there are duplicated "keys" in objects use this
// this will enumerate each object.
// ---------------------------------------------------------
var toObject = function(obj){
var newObj = {};
for(var i = 0; i<obj.length; i++){
newObj[i] = {}; // creates an empty object for each element
for(var k in obj[i]){
if(obj[i].hasOwnProperty(k)) {
newObj[i][k] = obj[i][k]; // set objects to those empty objects.
}
}
}
return newObj;
};
// example usage
var someThing = [
{'name': 'John', 'surname': 'Doe', 'age': 12},
{'name': 'Jane', 'surname': 'Doe', 'age': 47},
{'name': 'Ali', 'suranme': 'Yildiz', 'age': 25},
{'name': 'Hello', 'surname': 'World', 'age': 33}
];
toObject(someThing);
// Output
[object Object] {
0: [object Object] {
age: 12,
name: "John",
surname: "Doe"
},
1: [object Object] {
age: 47,
name: "Jane",
surname: "Doe"
},
2: [object Object] {
age: 25,
name: "Ali",
suranme: "Yildiz"
},
3: [object Object] {
age: 33,
name: "Hello",
surname: "World"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment