This is my object:
{Mary : 'Engineer', Jane : 'Doctor'}
I want to turn it into this format:
{[Name: 'Marry', Occupation: 'Engineer'], [Name: 'Jane', Occupation: 'Doctor']}
How can I do it with javascript?
var result = [];
var i = "";
for (i in yourJSON) {
// i is the key
result.push({Name: i, Occupation: yourJSON[i]});
}
from How to access key itself using javascript
greetings
i as a var before you use it (you're using a global right now).Just loop over the first object and place the elements where you want them.
var obj = {Mary : 'Engineer', Jane : 'Doctor'};
var people = [];
for(var name in obj){
var occ = obj[name];
people.push({Name: name, Occupation: occ});
}
The example object you show in your question uses invalid syntax. What you want is an array of objects, that's what this code does.
You want to loop over the keys in your data and make a new object for each, with the name and occupation properties. Something like:
function makeNameOccupation(data) {
return Object.keys(data).map(c => {
return {name: c, occupation: data[c]};
});
}
console.log(makeNameOccupation({Mary : 'Engineer', Jane : 'Doctor'}))
For each key in the original object (the person's name) you map that into an object with the name and occupation properties. Since you have the name (as the key), you can fetch the occupation from the original object with ease, and build the new record.
That can be minified, if you're into that sort of thing, into:
return Object.keys(data).map(c => ({name: c, occupation: data[c]}));
So you have an object that looks like this
var originalPeopleObj = {Mary : 'Engineer', Jane : 'Doctor'}
What you want to do, is get the list of people's names inside your object.
var names = Object.keys(originalPeopleObj);
This will create an array of people names
names = ["Mary", "Jane"];
Now, you have to map those names to their occupations inside the originalPeopleObj
var newPeople = [];
for(var i = 0; i < names.length ; i++) {
var peopleObj = {};
peopleObj[i].name = names[i];
peopleObj[i].occupation = originalPeopleObj[names[i]];
}
You can loop over the keys of the object and build a new array of objects.
var object = { Mary: 'Engineer', Jane: 'Doctor' },
result = Object.keys(object).map(function (key) {
return { Name: key, Occupation: object[key] };
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
[{name: 'Mary', occupation: 'Engineer'}, ...]