Iterate over the object to verify if the field contains an empty array, then output null

Looking for help with handling empty arrays in an object:

productDetails: {
    cislife: [],
    prime: []
  }

Is there a way to have null returned instead of an empty array if no values are available?

For example, I'd like to determine if either the 'cislife' or 'prime' array is empty and return null as the value. If 'prime' has values but 'cislife' does not, then I want to return the values for 'prime' and null for 'cislife'.

Any suggestions on how to tackle this issue?

Answer №1

You have the option to utilize Array.prototype.reduce in order to construct an object literal by replacing [] with null when necessary:

const productDetails = {
  cislife: [],
  prime: [],
  nonEmptyExample: [1, 2, 3],
  nonArrayExample: 'a string!'
};

const emptyArraysToNulls = o => {
  return Object.entries(productDetails).reduce((accum, entry) => {
    const [key, val] = entry;
    if (Array.isArray(val)) {
      accum[key] = val.length === 0 ? null : val;
    } else {
      accum[key] = val;
    }

    return accum;
  }, {});
};

console.log(emptyArraysToNulls(productDetails));

Answer №2

A clever method to generate the desired array without altering the original one is shown below:

const initialObject = {
  cislife: [],
  prime: [],
  nonArrayField: "I'm not an array, keep me as it is!"
};

const resultObject = {
  ...initialObject,
  ...Object.keys(initialObject)
    // remove keys that do not belong to empty arrays
    .filter(key => Array.isArray(initialObject[key]) && !initialObject[key].length)
    // replace empty arrays with null values
    .reduce((acc, key) => ({ ...acc, [key]: null }), {}),
};

console.log(resultObject);

Answer №3

One way to enhance your object editing skills is by utilizing getters

var productDetails = {
  _cislife: [],
  get cislife() {
    return this._cislife.length ? this._cislife : null
  },
  _prime: [],
  get prime() {
    return this.prime.length ? this.prime : null
  },
}

console.log(productDetails.cislife)

Answer №4

To access the data, utilize getter functions as shown below:

let customerData = {
    _loyaltyPoints: 150,
    _purchaseHistory: [],

    get loyaltyPoints() {
        return this._loyaltyPoints;
    },

    get purchaseHistory() {
        return this._purchaseHistory.length == 0 ? "No purchases made yet" : this._purchaseHistory;
    }
}

console.log(customerData.loyaltyPoints); // 150
console.log(customerData.purchaseHistory); // No purchases made yet

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

Trigger a jQuery click event to open a new tab

On a public view of my site, there is a specific link that can only be accessed by authenticated users. When an anonymous user clicks on this link, they are prompted to log in through a popup modal. To keep track of the clicked link, I store its ID and inc ...

What could be the reason for the email not being displayed in the form?

I am attempting to automatically populate the user's email in a form when a button is clicked, preferably when the page is loaded. However, I am encountering issues with this process. This project is being developed using Google Apps Script. Code.gs ...

The navigation is designed to only show up as I scroll down the page, but ideally it should be visible

I am trying to make the navigation bar appear on page load instead of when I scroll down the page. Currently, I am using this jQuery code: <script type="text/javascript> $(document).scroll(function() { if ($(this).scrollTop() == 20) { ...

Incorporating the values of JavaScript objects into a global variable

I'm currently developing a bank account program and facing a challenge in adding my direct debits (DDs) into the global variable. When I create new objects using my constructor function and add them into the bank account, only the last created DD is s ...

What is the best way to send parameters to a callback function in a jQuery $.getJSON method?

Currently, I am attempting to utilize jQuery to access a custom API using Ajax/$.getJSON. In my code, I am trying to send a specific value to the Ajax callback method, but I am encountering an issue where this value is not being properly passed and instea ...

Resolving TypeError: matchesSelector method is not recognized within React component

I am currently integrating masonry-layout from the official website to create a masonry grid within my component. However, I encountered an issue where clicking on a rendered element triggers the error message TypeError: matchesSelector is not a function. ...

How can I open the Ion-datetime view for the current year without allowing the selection of a specific day?

I am currently troubleshooting an issue with an Ionic date-time picker component. Upon opening the datepicker, it defaults to showing May 2021. As I scroll to the present date, I notice a circle highlighting today's date indicating that it selects th ...

I am uncertain about how to interpret this method signature

Can you help me determine the correct method signature for handleError? The linter tslint is indicating an error message that says expected call-signature: 'handleError' to have a typedef (typedef). Here is the code snippet in question: import ...

In Javascript, we can increment the current date by utilizing the `getDate()`

I am trying to create an if statement in JavaScript; if (nextProcessingDate > today ) { //do something } nextProcessingDate has a timestamp assigned, like 09/07/2014 12:10:17 To assign today's timestamp to the today variable, I am using this c ...

Unusual case of missing lines while reading a file using readline.createInterface()

const readline = require('readline') const fs = require('fs/promises'); (async function() { await fs.writeFile('/tmp/input.txt', [...Array(100000).keys()].join('\n')) await fs.writeFile('/tmp/other.tx ...

What happens if you try to add a member to a Mailchimp list who is already on the list

After following Angela Yu's course for the past few weeks, I attempted to implement the Mailchimp API as she demonstrates. However, I encountered difficulties due to recent changes in Mailchimp. Despite this setback, I was able to find the API referen ...

Formulation, on the other side of the comma

I have a calculation script that is almost working perfectly, but it seems to be ignoring values with decimal points. Can anyone offer some guidance on how to fix this issue? var selects = $('select'); var inputs = $('input'); selects. ...

What is the optimal method for saving and organizing data in SQL?

I currently have a MySQL table containing data that is displayed in an HTML table. Using JavaScript and drag & drop functionality, I am able to locally sort this table. My question is, what is the most effective method for saving these sorting changes? W ...

Transferring a JavaScript variable to C# to execute an SQL SELECT query, then sending the returned result back to JavaScript

I am facing an issue while trying to execute code in my Code Behind to query my SQL Server using a JavaScript variable and then return the result as an Integer back to my Javascript. My approach involves running some Javascript code initially to obtain a ...

Accessing an object's property within a mapped array in a Next.js application is possible

Currently, I am attempting to iterate through an array of objects and extract the link property as a <li></li> element. However, I am facing an issue where nothing is being returned: import { useState, useEffect } from "react"; import ...

Problem encountered while trying to import npm module in React Native

Working on developing an android app and currently in the process of importing the spotify-web-api-node module. In my index.android.js file, I have added the following line: import SpotifyWebApi from 'spotify-web-api-node'; However, when I try ...

Issues with fundamental JavaScript client-side code

As a newcomer to the world of javascript and jQuery, I am diving into my first experiment with javascript. My initial focus has been on changing questions by clicking next or previous buttons. The goal is to create a dynamic quiz webpage that updates quest ...

Cancelling an ongoing AWS S3 upload with Angular 2/Javascript on button click

I'm currently working with Angular 2 and I have successfully implemented an S3 upload feature using the AWS S3 SDK in JavaScript. However, I am now facing a challenge: how can I cancel the upload if a user clicks on a button? I've attempted the ...

Delete the designated column from the table

I am having difficulty with hiding and showing table columns using checkboxes. I need to eliminate the Mars column (in bold) along with its corresponding data (also in bold). Once the Mars column is removed, I want the Venus column and its data values to ...

NodeJS - The function app.listen is not defined in this context

I've come across a similar question before, but the answers provided didn't help me resolve my issue. The error message I'm getting is "TypeError: app.listen is not a function"; Here's my full code below. Thank you in advance for your ...