Access arrays/objects within main object using JavaScript's Object.keys()方法

Perhaps the title is a bit confusing, but I couldn't come up with a better way to phrase it.

I have a function that determines the value of each property within a contact object and returns 'No Data' if the value is null/empty/undefined. However, within each contact object, there is an 'Addresses' array containing address objects. I need to access the first/[0] index using a similar method so that manual creation of functions to search the values of each addressLine1, addressLine2 etc. property is not necessary.

In essence, I am looking to return 'No Data' for empty values of addressLine1, addressLine2, etc.

Here is an example structure of each object:

'Items': [
  {
    'property1': 'propertyValue',
    'property2': 'propertyValue',
    'property3': 'propertyValue',
    'addresses': [
      {
        'addressLine1': 'propertyValue',
        'addressLine2': 'propertyValue',
        'addressLine3': 'propertyValue',
      },
      {
        'addressLine1': 'propertyValue',
        'addressLine2': 'propertyValue',
        'addressLine3': 'propertyValue',
      },
      {
        'addressLine1': 'propertyValue',
        'addressLine2': 'propertyValue',
        'addressLine3': 'propertyValue',
      }
    ]
  }
]

The current code I have to access top level property values looks like this:

items.forEach(function(obj) {
    Object.keys(obj).forEach(function (property) {
        if (obj[property] === '' || obj[property] === null || obj[property] === undefined) {
            obj[property] = '*No Data*';
        }
    });
});

Answer №1

Recursion in action:

(function updateData(items){
 items.forEach(function(obj) {
 Object.keys(obj).forEach(function (property) {
    if (!obj[property]) {
        obj[property] = '*No Data*';
    }
    if(obj.addresses){
      updateData(obj.addresses);
    }
 });
 });
})(items);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can a JavaScript framework be created to ensure all browsers adhere to standards?

As someone who isn't an expert in JavaScript, I wonder if it's feasible to create a comprehensive embeddable JavaScript file that ensures all browsers adhere to standards. Could there be a compilation of known JavaScript hacks that compel each br ...

Converting lists to JSON format in a C# web form

Utilizing JSON.stringify, I have implemented textbox autocomplete for a web-form that suggests city names based on user input. The goal is to retrieve relevant city names from the database and display them as suggestions in the autocomplete feature after t ...

Creating default values for MongoDB databases using bdhash in Express.js and mongoose asynchronously

What is the best way to set a default value (like bdhash which is async) for a field in my mongoose schema? Currently, I am only seeing a promise inside. I'm using async/await correctly, but why does it seem like I'm getting just a promise? I als ...

Is it possible for a component to have multiple templates that can be switched based on a parameter?

Scenario My task is to develop a component that fetches content from a database and displays it on the page. There needs to be two components working together to create a single page, following a specific component tree structure. DataList - receives ful ...

What is the resolution if I need to utilize a property that is untyped?

Transitioning to TypeScript from plain old JavaScript is a step I'm taking because I believe it offers significant advantages. However, one drawback that has come to light is that not all attributes are typed, as I recently discovered. For instance: ...

React/Redux - Issue with rest operator functionality in component

Here is the initial state I am working with: const initialState = { selectedGroup: {}, groups: { rows: [], total: null }, offset: 0, range: 15, loading: false, error: null } Within a reducer function, I have this case for successful ...

Unraveling the mysteries of the Bootstrap carousel script

Hi everyone, I'm a newcomer to the world of JS and jQuery. Recently, while examining the code in carousel.js, I stumbled upon this particular line: this.cycle(true) The cycle function is structured like this: Carousel.prototype.cycle = function ...

How can I effectively monitor and track modifications to a document's properties in MongoDB?

I'm wondering how to effectively track the values of a document in MongoDB. This involves a MongoDB Database with a Node and Express backend. For example, let's say there is a document within the Patients collection: { "_id": "4k2lK49938d ...

Tips for selecting a "subset" within a foreach iteration

In my possession is an array made up of arrays $person = array(2) { [billy]=> array(3) { ["height"]=> string(60) "tall" ["build"]=> string(7) "slim" ["attractiveness"]=> s ...

Implementing a function or template from one component into another within a Vue.js application, despite lacking a direct connection between the two components

Working on my Vue.js app, I encountered an interesting challenge: The layout of the app is simple: it consists of a header, a main view, and a navigation section at the bottom. Depending on the current page the user is on, I want to display a main action ...

step-by-step guide on implementing autocomplete using google.maps.places.autocomplete in ExtJS

Just to clarify... I initially wrote a code that was error-free before editing this post. However, after reading a comment on creating a Minimal, Complete, and Verifiable example, I became confused. My minimal script did not work properly, I couldn't ...

The header row in my table multiplies each time an AJAX call is made

HeaderRowMultiplesEachTimeAjax My web grid table in JavaScript consists of a complete HTML table. The top header, which acts like a colgroup caption table, is built through JavaScript insertion as shown below: var headerRow = "<tr><th colspan=&a ...

Unusually Elevated Frame Rates within Three.js

I just launched a new website yesterday, which is dedicated to live editing three.js examples. I noticed that whenever I make updates to the code or switch between different example files, the frame rate of the site jumps up to around 1000 f/s. You can fi ...

Personalized AWS Cognito: Strategies for Tailoring Input Field Designs

MY CURRENT CHALLENGE: Within my Vue application, I am utilizing the AWS authenticator for managing login and signup processes. However, customizing its style has proven to be difficult due to the structure being built with shadow DOM elements. https://i. ...

The passport is experiencing an authentication issue: The subclass must override the Strategy#authenticate method

After attempting to authenticate and log in a user, I encountered an error message stating: Strategy#authenticate must be overridden by subclass. How can I resolve this issue? What could be causing this error to occur? Concerning Passport.js const LocalS ...

Modifying text on input buttons using Javascript

Including product names, text forms, and buttons on a webpage is essential for showcasing products effectively. Each product is assigned an ID such as p1, p2, etc., while the input types are identified by i1, i2, etc. When users enter information into the ...

Exploring the concept of Promises through the lens of recursion

I am dealing with a MongoDB collection that looks like this [ { "classId": "1", "name": "Input", "definition": [ { "property": [ { "classId": "12", "name": "One" }, { ...

Create a new 2D array with a specific number of elements

I have a 2-dimensional array of double numbers that is 48 by 48. Currently, I am attempting to create a method that allows the user to specify a particular amount, for example, 7 by 7, and then transfer that data to a new 2-dimensional array. public stati ...

What is the most effective way to extract the output from a JSONP request and utilize it beyond the

I have a function that is working well. I had to use JSONP to handle cross-domain issues, and I also wrote an HTTP module to change the content-type. However, I did not include a callback name in the URL. function AddSecurityCode(securityCode, token) { va ...

Using tokens to make consecutive API calls in JavaScript/Node.js

After generating the token, I need to make sequential calls to 5 different APIs. The first API used to generate the token is: POST https://idcs-xxxx.identity.c9dev2.oc9qadev.com/oauth2/v1/token Using the username and password, I will obtain the token from ...