Jaybruh
Jaybruh

Reputation: 343

How to map through a object array while it is uncertain if all fields in the object exist?

I need to get single object values from an array which contains many (nested) objects and save these values in a new array. This works fine with map like:

var newArrayA = array.map(x => x.PI[0].ZZ);
var newArrayB = array.map(x => x.FS.CC.FR);
var newArrayC = array.map(x => x.FS.BD.FR);

In case all objects contain all values as you can see here:

var array =
     [ 
      { _id: 'MEuDZjQDw8XQk4ny7Y',
         PI: [        
              {ZZ: "ABC"}
             ],
         FS:
          { CC: {FR: 1},
            BD: {FR: 2} 
          }
       },
       { _id: 'gFsya9tHMAkAoPgvw',
         PI: [        
              {ZZ: "DEF"}
             ],
         FS:
          { CC: {FR: 3},
            BD: {FR: 4} 
          }
       }
     ]

There could be many more 'id' objects as well as more fields within the data structure of the array. However, I receive an error if for example the second object does not contain a FS field:

var array =
 [ 
  { _id: 'MEuDZjQDw8XQk4ny7Y',
     PI: [        
          {ZZ: "ABC"}
         ],
     FS:
      { CC: {FR: 1},
        BD: {FR: 2} 
      }
   },
   { _id: 'gFsya9tHMAkAoPgvw',
     PI: [        
          {ZZ: "DEF"}
         ]
   }
 ]

The problem is that I still need to get the FS.CC or FS.BD values from the objects which contain these values. It would be perfectly fine if I get a "empty or "undefined" in case the values are not in an object and the values if they are in the object:

var neededNewArrayC = [2, "empty"];

Or is there maybe another solution?

Upvotes: 0

Views: 41

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075199

You can use an && guard:

var newArrayB = array.map(x => x.FS && x.FS.CC && x.FS.CC.FR);
// ----------------------------^^^^^^^^^^^^^^^^^^^

If x doesn't contain FS, x.FS will be undefined, and the && expression will short-circuit with undefined as its value. The same for x.FS.CC. But if x.FS.CC exists (and isn't falsy), the result will be the value of x.FS.CC.FR.

Example:

var a = [
  { // Has everything
    FS: {
      CC: {
        FR: "the FR value"
      }
    }
  },
  { // No .FS.CC
    FS: {
    }
  },
  { // No .FS
  }
];
console.log(a.map(x => x.FS && x.FS.CC && x.FS.CC.FR));

Upvotes: 4

Related Questions