Reputation: 838
I've got an Object with variable propertie names and im converting it into an array:
var test = Object.getOwnPropertyNames(obj); //[a, b, c]
Now I've got my array of Property names. The next step I want to take is to turn this array into an Array of objects like this:
newObj= [ { "name": a }, {"name": b} , {"name" : c }]
How can I achieve that?
Upvotes: 0
Views: 41
Reputation: 92854
Simple approach without getOwnPropertyNames
function(using Object.keys
function):
// obj is your initial object
var newArr = Object.keys(obj).map(function(k) { return { name: k }; });
Upvotes: 1
Reputation: 68393
Try this (using Object.getOwnPropertyNames
itself)
var obj = { a :1, b:2, c:3 };
var output = Object.getOwnPropertyNames(obj).map( function( key ){
return { "name" : obj[ key ] } ;
});
console.log(output);
Upvotes: 1
Reputation: 34189
You can utilize Array.prototype.map
- it transforms sequence into a new array by applying a function to each item, which is wrapping to an object with name
property in your case:
var names = ["a", "b", "c"];
var newObj = names.map(function(n) { return { name: n }; });
console.log(newObj);
Combining with your getOwnPropertyNames
usage, it can look like:
var newObj = Object.getOwnPropertyNames(obj).map(function(n) { return { name: n }; });
Upvotes: 2