-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.

3
  • Object.entries(obj).map(e => Object.fromEntries([e])), Object.fromEntries(arr.flatMap(o => Object.entries(o))) Commented Feb 2, 2023 at 11:39
  • The format in this question is different than in the supposed duplicate Commented Feb 2, 2023 at 11:42
  • I answered in the linked question: stackoverflow.com/a/75322735/1871033 Commented Feb 2, 2023 at 11:47

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.