0

I have this variable:

let json1 = 
{'aaa': {'cus1':1,'cus2':2},
 'bbb': {'cus3':1,'cus4':5}
}

And I would like to convert it into the following array:

[{'aaa': {'cus1':1,'cus2':2}},
 {'bbb': {'cus3':1,'cus4':5}}
]

What I tried to do is:

let arr = [];
let keys = Object.keys(json1);
keys.reduce((acc, key) => {
        acc.push({key: json1[key]});
        return acc;
    }, arr);

While I get:

[ { key: { cus1: 1, cus2: 2 } }, { key: { cus3: 1, cus4: 5 } } ]

So evidently I would like to use the true key instead of key as the key of my encapsulated json in the arr.

P.S. Is there any way to do this without using for loop?

0

2 Answers 2

2

Your issue is here:

acc.push({key: json1[key]});
//        ^
//        here

In this context key is literally the name of the property. However what you are looking for is to evaluate key as the name of your property (aka computed property name):

acc.push({[key]: json1[key]});
//        ^
//        now your property name is whatever `key` value is

A simple example:

var key = '🌯';
var obj = {[key]: true};

obj;
//=> { "🌯": true }

Now to answer your question:

const split =
  obj =>
    Object.entries(obj)
      .map(([k, v]) =>
        ({[k]: v}));

split({ aaa: {cus1: 1, cus2: 2}
      , bbb: {cus3: 1, cus4: 5}
      });

//=> [ { aaa: {cus1: 1, cus2: 2} }
//=> , { bbb: {cus3: 1, cus4: 5} }
//=> ]

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

2 Comments

The image in the answer is unnecessary imo, and could be replace with one additional line obj; //=> { "🌯": true } in the code block above it.
@3limin4t0r Sure. Done.
1

You could take the separated key/value pair to a new object with the given key.

const
    data = { aaa: { cus1: 1, cus2: 2 }, bbb: { cus3: 1, cus4: 5 } },
    array = Object.entries(data).map(([k, v]) => ({ [k]: v }));
    
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.