Skip to content

Instantly share code, notes, and snippets.

@eperedo
Last active June 15, 2017 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eperedo/03916670c1ceea866ae438fde6d37225 to your computer and use it in GitHub Desktop.
Save eperedo/03916670c1ceea866ae438fde6d37225 to your computer and use it in GitHub Desktop.
Convert an array of json objects to an object. I KNOW!
var a = [{"id": 42, "name": "TALLA", "companyId": 40, "createdAt": "2017-02-13T21:51:15.000Z", "updatedAt": "2017-02-13T21:51:15.000Z", "flagActive": 1}, {"id": 37, "name": "TELA", "companyId": 40, "createdAt": "2017-02-13T21:23:11.000Z", "updatedAt": "2017-02-13T21:23:11.000Z", "flagActive": 1}, {"id": 38, "name": "TIPO DE PRENDA", "filterable": true}, {"id": 39, "name": "MODELO", "filterable": true}, {"id": 41, "name": "COLOR", "filterable": true}, {"id": 40, "name": "MANGA", "filterable": true}]
function transformArrayToObject(array) {
var b = {};
array.forEach((item, index) => {
var keys = Object.keys(item);
b[item.id] = {};
keys.forEach((key) => {
b[item.id][key] = item[key];
});
});
return b;
}
console.log(transformArrayToObject(a))
var obj = {
42: {
"id": 42,
"name": "TALLA",
},
37: {
"id": 37,
"name": "TELA",
},
};
function convertObjectToArray(obj) {
var array = [];
var keys = Object.keys(obj);
keys.forEach((key) => {
var objKeys = Object.keys(obj[key]);
var newObj = {};
objKeys.forEach((propertyName) => {
newObj[propertyName] = obj[key][propertyName];
});
array.push(newObj);
});
return array;
}
console.log(convertObjectToArray(obj));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment