I'm working with this array of nested objects, getted from an API:
const myObj = [
{
"$id":"1",
"Description":"WA State",
"Place":"WA",
"Data":[
{
"$id":"2",
"Description":"Years",
"Indicators":[
{
"$id":"3",
"Year":2017,
"Points":22191,
"Goal":"28000",
"Description":"Year 2017"
},
{
"$id":"4",
"Year":2018,
"Points":25994,
"Goal":"28000",
"Description":"Year 2018"
}
]
},
{
"$id":"5",
"Description":"Local Goal",
"Indicators":[
{
"$id":"6",
"Year":2018,
"Points":25994,
"Goal":"28000",
"Description":"Year 2018"
}
]
},
{
"$id":"7",
"Description":"Remote Goal",
"Indicators":[
{
"$id":"8",
"Year":2018,
"Points":55857,
"Goal":"84000",
"Description":"Year 2018"
}
]
}
]
},
{
"$id":"9",
"Description":"NY State",
"Place":"NY",
"Data":[
{
"$id":"10",
"Description":"Years",
"Indicators":[
{
"$id":"11",
"Year":2017,
"Points":23451,
"Goal":"27000",
"Description":"Year 2017"
},
{
"$id":"12",
"Year":2018,
"Points":21953,
"Goal":"26000",
"Description":"Year 2018"
}
]
},
{
"$id":"13",
"Description":"Local Goal",
"Indicators":[
{
"$id":"14",
"Year":2018,
"Points":24195,
"Goal":"25000",
"Description":"Year 2018"
}
]
},
{
"$id":"15",
"Description":"Remote Goal",
"Indicators":[
{
"$id":"16",
"Year":2018,
"Points":80857,
"Goal":"90000",
"Description":"Year 2018"
}
]
}
]
}
];
I need to delete all the $id
and Description
properties from the objects, but not mutating the object. I'm trying to do it using .reduce()
:
const props = ['$id', 'Descripcion'];
function removeKeys(obj, prop){
return props.map( (prop, index) => Object.keys(obj).reduce((object, key) => {
if (key !== prop[index]) {
object[key] = obj[key]
}
if(object.hasOwnProperty(key))
removeKeys(obj, prop[index])
return object
}, {})
)
}
console.log( removeKeys(myObj, props) );
// RangeError: Maximum call stack size exceeded
And does not works. Any ideas on how I can achieve this using .reduce()
PD: My question is not a duplicate of, because I'm mentioning and specifying the use of reduce
to achieve the goal. In the other question, the answers are about using the "for...loop"
syntax.