-2

I have the following object in my code.

    [
{
"Name": "John Johnsson",
"Adress": "Linkoping",
"Id": 0,
"Age": "43",
"Role": "Software Engineer"
},
{
"Name": "Marcus Svensson",
"Adress": "Norrköping",
"Age": "26",
"Id": 1,
"Role": "Project Manager"
},
{
"Age": "25",
"Name": "Trevor McNoah",
"Id": 2,
"Adress": "Stockholm",
"Role": "CTO"
}
]

How do I best delete all the "Adress" fields? So I end up with the following result. I've been struggling to find an answer to this basic question.

[
{
"Name": "John Johnsson",
"Id": 0,
"Age": "43",
"Role": "Software Engineer"
},
{
"Name": "Marcus Svensson",
"Age": "26",
"Id": 1,
"Role": "Project Manager"
},
{
"Age": "25",
"Name": "Trevor McNoah",
"Id": 2,
"Role": "CTO"
}
]

3 Answers3

1

JavaScript has delete operator:

data.forEach(item => {
  delete item['Address'];
})

You can read more about delete operator here.

Maksym Shcherban
  • 742
  • 4
  • 13
1

You can do it like that: so you don't mutate the initial array.

const listWithoutAddress = list.map(({Adress, ...rest}) => ({...rest}));

0

To remove a property from a js object you can use the delete command, like this:

let arr =  [
{
"Name": "John Johnsson",
"Address": "Linkoping",
"Id": 0,
"Age": "43",
"Role": "Software Engineer"
},
{
"Name": "Marcus Svensson",
"Address": "Norrköping",
"Age": "26",
"Id": 1,
"Role": "Project Manager"
},
{
"Age": "25",
"Name": "Trevor McNoah",
"Id": 2,
"Address": "Stockholm",
"Role": "CTO"
}
];

console.log(arr);

arr.forEach(_=>{delete _.Address}); // <-- this is it

console.log(arr);
Francesco Rogo
  • 167
  • 2
  • 8