I have read several solutions to this problem here. When I try it, I continue to receive an error for the pop() method.
I have what is essentially a multidimensional array in javascript. I am tasked with returning the array with the sensitive info removed (e.g. remove the SSN, in this example)
I thought I could use a foreach loop, and the pop() function to remove the last element of the child arrays, the SSN.
testing it using node on the commandline, the stdout is telling me that element.pop() is not a function. i've tried it with pop(), slice(), filter(), all with no success.
when running $> node filename.js
H:\Apache2\htdocs\test\filename.js:50 noppi[i] = element.pop(); ^
TypeError: element.pop is not a function
let recs = [
{
ID: 1,
NAME: 'John',
EMAIL: '[email protected]',
SSN: '123'
}, {
ID: 2,
NAME: 'Sally',
EMAIL: '[email protected]',
SSN: '456'
}, {
ID: 3,
NAME: 'Angie',
EMAIL: '[email protected]',
SSN: '789'
}
];
let i = 0;
let noppi = [];
recs.forEach(element => {
noppi[i] = element.pop();
i ;
});
console.log(noppi);
CodePudding user response:
At the risk of sounding redundant, I'll briefly reiterate what the earlier answers have already stated.
The input data structure isn't a multi-dimensional array , it's an array of objects [ [ ... ], [ ... ] ]
[ {...}, {...} ]
. So you can't use Array methods like .pop()
on the objects {...}
.
Here's a simple one-liner that uses .forEach()
and delete
.
recs.forEach(obj => delete obj.SSN)
delete
is an operator with one purpose: to remove an object's property like for example SSN: '123-45-6789'
. Simple and perfect.
Note, .forEach()
mutates the array, meaning that it's the original data being changed (see Minja's comment).
let recs = [
{
ID: 1,
NAME: 'John',
EMAIL: '[email protected]',
SSN: '123'
}, {
ID: 2,
NAME: 'Sally',
EMAIL: '[email protected]',
SSN: '456'
}, {
ID: 3,
NAME: 'Angie',
EMAIL: '[email protected]',
SSN: '789'
}
];
recs.forEach(obj => delete obj.SSN);
console.log(recs)
CodePudding user response:
As per your need you need to remove SSN from your object, try below code it should work for you.
recs.forEach(element => {
const { SSN, ...rest } = element;
noppi.push(rest);
});
Here we are removing SSN from object and rest will push in noppi.
CodePudding user response:
Try this:
recs.forEach(element => {
noppi.push = element;
});
You are trying to use pop() on an object not an array