Herba
Herba

Reputation: 11

Converting array object to pairs object in javascript

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"}]

Upvotes: 1

Views: 59

Answers (3)

Reality
Reality

Reputation: 677

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.

Upvotes: 0

Alex Pereverzyev
Alex Pereverzyev

Reputation: 31

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

Upvotes: 3

Hassan Imam
Hassan Imam

Reputation: 22564

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

Upvotes: 3

Related Questions