Rich
Rich

Reputation: 185

How to convert data from one format to other js

I am working on a project and I am getting the below data

{
  a1: { target: 'a2', overwrite: true },
  aa1: { target: 'aa2', overwrite: true },
  aaa1: { target: 'aaa2', overwrite: false }
}

I want to convert the above as below

[
  { source: 'a1', target: 'a2', overwrite: 'on' },
  { source: 'aa1', target: 'aa2', overwrite: 'on' },
  { source: 'aaa1', target: 'aaa2' }
]

How can I achieve this? Since I am new to js I am confused about this. Can anyone help?

Upvotes: 0

Views: 49

Answers (2)

Georgy
Georgy

Reputation: 1939

const obj = {
  a1: { target: 'a2', overwrite: true },
  aa1: { target: 'aa2', overwrite: true },
  aaa1: { target: 'aaa2', overwrite: false }
}

Object.keys(obj).map(key => ({
  source: key,
  target: obj[key].target,
  ...(obj[key].overwrite && { overwrite: 'on' }),
}))

Upvotes: 6

Robby Cornelissen
Robby Cornelissen

Reputation: 97150

Just use Object.entries() with map():

const data = {
  a1: { target: 'a2', overwrite: true },
  aa1: { target: 'aa2', overwrite: true },
  aaa1: { target: 'aaa2', overwrite: false }
};

const result = Object.entries(data).map(([source, {target, overwrite}]) => ({
  source,
  target,
  ...(overwrite && { overwrite: 'on' })
}));

console.log(result);

Upvotes: 3

Related Questions