Reputation: 113
The question is pretty simple and has no clear response. I have an object my goal is to take each value and key transform them to object and push to the array, for example below to make it clear.
{
title: "This is a Title",
name: "This is a name"
}
Transform to.
[
{title: "This is a Title"},
{name: "This is a name"}
]
Upvotes: 0
Views: 57
Reputation: 139
Love how clean the existing solutions are, but if you need to handle high amounts of data, a solution like this will provide much better performance:
function transform(obj) {
let arr = []
for (let key in obj) {
let temp = {}
temp[key] = obj[key]
arr.push(temp)
}
return arr
}
let data = {
title: "This is a Title",
name: "This is a name"
}
console.log(transform(data))
Edit: Figured out how to use code snippets :)
Upvotes: 0
Reputation: 72837
Use Object.entries
to convert the object to an array, then map the array to an array of objects in the format you want:
const obj = {
title: "This is a Title",
name: "This is a name"
};
const arr = Object.entries(obj)
.map(([key, value]) => ({ [key]: value }));
console.log(arr);
Upvotes: 6
Reputation: 386540
You could map the entries of the object by using any entry for a new object.
const
data = { title: "This is a Title", name: "This is a name" },
result = Object
.entries(data)
.map(e => Object.fromEntries([e]));
console.log(result);
Upvotes: 2