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?
CodePudding user response:
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' }),
}))
CodePudding user response:
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);