• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Filter out element in a deeply nested array

tdev81

New Coder
Context: I have a form where a user enters in data. I want to remove all object elements in the phone array that contain an empty string in the phoneNumber property.

Here is example data:

JavaScript:
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.

JavaScript:
const newData = data.
      .map((array) => array)
      .forEach((contactObject) => {
        return contactObject.phone.filter(
          (phoneArray) => phoneArray.phoneNumber !== ""
        );
      });
    console.log("newData: ", newData);

Any clue on what I'm doing wrong?
 
Last edited:

menator01

King Coder
This works for me

JavaScript:
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: ""}
                   ]
  }
]

for (let i=0; i<data.length; i++){
    console.log(data[i]['contactName']);
    for (let j=0; j<data[i]['phone'].length; j++) {
        if (data[i]['phone'][j]['phoneNumber'] != ''){
            console.log(data[i]['phone'][j]['phoneName']);
            console.log(data[i]['phone'][j]['phoneNumber'])
        }
    }
    console.log('')
}

Output

Code:
Contact 1 Name
Some Name
(111) 111-1111
Some Name2
(222) 222-2222

Contact 2 Name
Some Name
(333) 333-3333
Some Name2
(444) 444-4444
 
Last edited:
Top