There are multiple fields in an object like this.
{
"image-processing": {
"type": "lib",
"data": {
"files": [
{
"file": "libs/photography/processing/.babelrc",
"hash": "62d50f586b2880f9d58ca4e9a84914c6a0d4936d"
},
{
"file": "libs/photography/processing/src/lib/processing.ts",
"hash": "a285d3554f264cc60f35bef6180298badb0478d1",
"deps": [
"npm:gm",
"npm:mongodb"
]
}
]
}
},
"image-processing-2": {
"type": "lib",
"data": {
"files": [
{
"file": "libs/photography/processing/.babelrc",
"hash": "62d50f586b2880f9d58ca4e9a84914c6a0d4936d",
"deps": [
"npm:gm",
"npm:faker"
]
},
{
"file": "libs/photography/processing/src/lib/processing.ts",
"hash": "a285d3554f264cc60f35bef6180298badb0478d1",
"deps": [
"npm:gm",
"npm:mongodb"
]
}
]
}
}
}
I only need the type and the content of data.files.deps as value object for the key.
As you can see each file has an optional deps array. All deps values should be merged.
So the result should be:
{
"image-processing": { type: "lib", packages: [ "npm:gm", "npm:mongodb" ] },
"image-processing-2": { type: "lib", packages: [ "npm:faker", "npm:gm", "npm:mongodb" ] }
}
I tried to iterate through the object, but this would overwrite the value instead of adding new package names to the value:
const result = {}
Object.entries(data).map(([key, value]) => {
result[key].type = value.type
result[key].packages = value?.data?.files.map(d => d.deps)
})
>Solution :
Use flatMap instead of map so that you have a flattened array of dependency strings – and alternate with the empty array so that undefined .deps properties don’t cause problems.
const data={"image-processing":{type:"lib",data:{files:[{file:"libs/photography/processing/.babelrc",hash:"62d50f586b2880f9d58ca4e9a84914c6a0d4936d"},{file:"libs/photography/processing/src/lib/processing.ts",hash:"a285d3554f264cc60f35bef6180298badb0478d1",deps:["npm:gm","npm:mongodb"]}]}},"image-processing-2":{type:"lib",data:{files:[{file:"libs/photography/processing/.babelrc",hash:"62d50f586b2880f9d58ca4e9a84914c6a0d4936d",deps:["npm:gm","npm:faker"]},{file:"libs/photography/processing/src/lib/processing.ts",hash:"a285d3554f264cc60f35bef6180298badb0478d1",deps:["npm:gm","npm:mongodb"]}]}}};
const output = Object.fromEntries(
Object.entries(data).map(([key, value]) => [
key,
{
type: 'lib',
packages: [...new Set(value.data.files.flatMap(file => file.deps ?? []))]
}
])
);
console.log(output);