-2

I have the below object

input = {a:1, b:2, c:3}

I want to covert it into the following

Output = [{ a: 1 }, { b: 2 }, { c: 3 }]

Also provide solution to vice versa i.e. array of objects to object.

I have tried using built-in methods like Object.entries but not getting the perfect solution.

  • 1
    Welcome to Stack Overflow! Please visit the [help], take the [tour] to see what and [ask]. Do some research - [search SO for answers](https://www.google.com/search?q=javascript+convert+object+to+object+array+site%3Astackoverflow.com). If you get stuck, post a [mcve] of your attempt, noting input and expected output using the [\[<>\]](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Feb 02 '23 at 11:36
  • `Object.entries(obj).map(e => Object.fromEntries([e]))`, `Object.fromEntries(arr.flatMap(o => Object.entries(o)))` – CherryDT Feb 02 '23 at 11:39
  • The format in this question is different than in the supposed duplicate – Moritz Ringler Feb 02 '23 at 11:42
  • I answered in the linked question: https://stackoverflow.com/a/75322735/1871033 – CherryDT Feb 02 '23 at 11:47

2 Answers2

0

Use Object.entries() to get key/value tuples and format them as you need:

const input = {a:1, b:2, c:3}
const res = Object.entries(input).map(([key, value]) => ({[key]: value}))
console.log(res)
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
0

You can use Object.entries to get the key and value pair and then form the object from them.

And to convert the obj from an array, you can just iterate to the array and create an object from them.

You can check this solution.

input = {a:1, b:2, c:3}

function obj2arr(obj) {
    return Object.entries(obj).map(([key, value]) => {
        return {[key]: value}
    })
}

function arr2obj(arr) {
    return arr.reduce((resObj, obj) => {
        return {...resObj, ...obj};
    }, {});
}

const arr = obj2arr(input);
const obj = arr2obj(arr);

console.log(arr);
console.log(obj);
Sifat Haque
  • 5,357
  • 1
  • 16
  • 23