LearningReact
LearningReact

Reputation: 113

Formating an Object to All Array of objects

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

Answers (3)

Xintaur
Xintaur

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

Cerbrus
Cerbrus

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

Nina Scholz
Nina Scholz

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

Related Questions