Last active
June 15, 2017 19:28
-
-
Save eperedo/03916670c1ceea866ae438fde6d37225 to your computer and use it in GitHub Desktop.
Convert an array of json objects to an object. I KNOW!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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