How to delete keys an a Array of Docs

Viewed 37

Is there a simple way to only return a few keys in my case for example i want to only return headername, field and type if it exists. I know i can delete keys via

for (i = 0; i < obj.length; i++) {
  delete obj[i]['type']
  delete obj[i]['hide']
  delete obj[i]['position']
}

which would mean i would have to loop over all docs in array and delete the keys but not sure if there is a simpler faster way to achieve the same. In my case this doc will never be huge as it only stores column definitions for export of data

[   {
             "headerName": "assessed_combined_value",
             "field": "assessed_combined_value",
             "hide": false,
             "position": 8,
             "type": "money"
        },
        {
             "headerName": "assessee1",
             "field": "assessee1",
             "hide": false,
             "position": 1
        },
        {
             "headerName": "assessee2",
             "field": "assessee2",
             "hide": false,
             "position": 2
        },
        {
             "headerName": "bathrooms",
             "field": "bathrooms",
             "hide": false,
             "position": 5
        }
        ]
2 Answers

You can use destructuring

let data = [{"headerName": "assessed_combined_value","field": "assessed_combined_value","hide": false,"position": 8,"type": "money"},{"headerName": "assessee1","field": "assessee1","hide": false,"position": 1},{"headerName": "assessee2","field": "assessee2","hide": false,"position": 2},{"headerName": "bathrooms","field": "bathrooms","hide": false,"position": 5}]

let final = data.map(({field, headerName}) => ({headerName, field}))

console.log(final)

If the case is vice-versa you want to leave only some of properties behind and want to select all other properties you can use spread syntax i.e if you want to leave out only field key

let final = data.map(({field, ...rest}) => rest)

You can use the spread operator combining with the previously posted answer to show only those fields which are present in the currently iterated object.

let info = [{
    "headerName": "assessed_combined_value",
    "field": "assessed_combined_value",
    "hide": false,
    "position": 8,
    "type": "money"
},
{
    "headerName": "assessee1",
    "field": "assessee1",
    "hide": false,
    "position": 1
},
{
    "headerName": "assessee2",
    "field": "assessee2",
    "hide": false,
    "position": 2
},
{
    "headerName": "bathrooms",
    "field": "bathrooms",
    "hide": false,
    "position": 5
}]

const result = info.map(({field, headerName, type}) => ({
    ...(headerName && {"headerName": headerName}),
    ...(field && {"field": field}),
    ...(type && {"type": type})
}));
console.log(result);

Related