tdev81
January 18, 2023, 10:24am
#1
Context: I have a form where a user enters in data. I want to filter out any objects that might contain empty strings.
Here is example data and the solution I thought would work.
const data =
[
{
contactName: "Contact 1 Name",
phone: [
{phoneName: "Some Name", phoneNumber: "(111) 111-1111"}
{phoneName: "Some Name2", phoneNumber: "(222) 222-2222"}
{phoneName: "Some Name2", phoneNumber: ""}
]
},
{
contactName: "Contact 2 Name",
phone: [
{phoneName: "Some Name", phoneNumber: "(333) 333-3333"}
{phoneName: "Some Name2", phoneNumber: "(444) 444-4444"}
{phoneName: "Some Name2", phoneNumber: ""}
]
}
]
Here is the solution I have come up with but when I console.log(newData), I get undefined.
const newData = data.
.map((array) => array)
.forEach((contactObject) => {
return contactObject.phone.filter(
(phoneArray) => phoneArray.phoneNumber !== ""
);
});
console.log("newData: ", newData);
I want the exact same data structure but I want to remove the phone objects in the phone array that contain empty phoneNumber properties. Any clue on what I’m doing wrong?
tdev81:
remove the object’s
for clarity; you want to remove the ENTIRE contact if you see a single empty phone number? or you want to remove the entry in the phone array?
tdev81
January 18, 2023, 10:42am
#3
I just want to remove the entry in the phone array, not the entire contact.
Manipulate only the array you’re trying to.
data.forEach((entry) => {
entry.phone = entry.phone.filter((number) => number.phoneNumber != "");
});
Remember that the elements inside a constant array are still mutable; you dont need to define a new object to replace the existing one.
1 Like
tdev81
January 18, 2023, 1:00pm
#5
Thanks for your help. Any clue how to get this to output to the console like the original data array with two contact objects? This still gives me undefined:
console.log(
"forum solution: ",
data.forEach((contactObject) => {
contactObject.phone = contactObject.phone.filter((number) => number.phoneNumber != "");
})
);
I am able to return a separate console.log for each array via this, but I’m trying to get the original structure.
console.log(
"forum solution: ",
data.forEach((contactObject) => {
console.log(
(contactObject.phone = contactObject.phone.filter(
(number) => number.phoneNumber != ""
))
);
})
);
So… uh… stares at
I would just…modify the object, then output the object. Dont try and combine the two steps.
data.forEach((entry) => {
entry.phone = entry.phone.filter((number) => number.phoneNumber != "");
});
console.log(data);
1 Like
tdev81
January 18, 2023, 1:04pm
#7
The data array is actually part of an input to a mutation API so I’m trying to keep the structure exactly the same so the API doesn’t need tweaked.
tdev81
January 18, 2023, 1:06pm
#8
You’re right that works. Awesome thank you!!!
2 Likes