1

I have an object like the one below.

var data = {data1:"test",data2:"test2"}

How can I convert this to the following object?

[{data1:"test"},{data2:"test2"}]

3 Answers 3

3

You can use Object.entries() with array#map to generate an array of objects from your object.

const data = { data1:"test", data2:"test2" },
      result = Object.entries(data).map(([key, value]) => ({[key]: value}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

3

JavaScript objects are dictionaries, you can use Object.keys to put object property names into an array and then map each array item to a new object like this:

var result = Object.keys(data).map(k => ({ [k]: data[k] }));

3 Comments

Add an explanation, please.
Object.keys(data) returns keys in object as [data1, data2 ]. map iterate over the array and also return an array. here k is a key from [data1, data2 ]. then in map, he prepared a { [k]: data[k] } that is appending in the array will be return by map.
for...in also works, but yeah I would definitely recommend using more "native" ways to iterate over objects.
0

Old school way:

const data = {data1:"test",data2:"test2"};
let result = [];
for(let key in data){
  result.push({[key]: data[key]});
}
console.log(result);

New way (use Object.Keys, like mentioned in another answer. It's different on purpose to encourage uniqueness. For more "compact" and "resource-efficient" code use the other answer mentioned by Alex Pereverzyev):

const data = { data1:"test", data2:"test2" }
const result = [];
//This returns the keys of data ("data1", "data2"). Then use bracket notation to find the value in the object (data["data1"]):
Object.keys(data).forEach(key => {
  //Push into the array the name of the key along with its value
  result.push({[key]: data[key]})
});
console.log(result);

Please note that there are many ways to do this, the ones I mentioned are just a few.

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.