Reputation: 3509
How can I convert the following object:
{
Value1: 1,
Value2: 3
}
into an array that looks like this:
[
{name: Value1, position: 1},
{name: Value2, position: 3}
]
I've tried using Object.keys
, but didn't really get the desired results.
Upvotes: 0
Views: 77
Reputation: 5020
function convertToArray(obj){
return Object.keys(obj).map(prop => {
return {
name: prop,
position: obj[prop]
};
});
console.log(convertToArray({ Value1: 2}));
Upvotes: 0
Reputation: 10204
You can get the array of [key, value]
pairs using Object.entries
function.
const input = {
Value1: 1,
Value2: 3
};
const output = Object.entries(input).map((item) => ({
name: item[0],
position: item[1]
}));
console.log(output);
Upvotes: 2