What is the most effective method for disregarding undefined values?

Implementing a project using Vue.js and Vuex, I am retrieving data from an API that functions as a content-management system. The product class in the CMS possesses numerous properties that can be populated by the user, such as;

{
  "title": "Handbrause rot",
  "price": 500,
  "description": "Hello World",
  ...
}

and more. To streamline my application, I aim to normalize the object properties since not all are necessary:

const normalizedProducts = [];
for (let i = 0; i < allProducts.length; i++) {
  const normalizedProduct = {
    productId: allProducts[i].id,
    slug: allProducts[i].slug,
    productType: allProducts[i].product_type,
    title: allProducts[i].title,
    description: allProducts[i].description,
    teaser_image: allProducts[i].teaser_image,
    images: allProducts[i].images,
    new: allProducts[i].new,
    topseller: allProducts[i].topseller,
    brand: allProducts[i].brand
  }
  normalizedProducts.push(normalizedProduct);
  return normalizedProducts;
}

The issue arises when empty fields in the API return as undefined. This causes problems where if one property is undefined, the entire program crashes with errors like

TypeError: null is not an object (evaluating 'allProducts[i].brand]')
.

While it's possible to implement if-clauses or try-catch statements for each property to prevent crashing, is there a cleaner solution to this dilemma?

Sample data:

[
  {
    productId: 1,
    slug: 'One',
    productType: 'Two',
    title: undefined,
    description: 'Three',
    teaser_image: 'Four',
    images: 'Five',
    new: undefined,
    topseller: undefined,
    brand: undefined,
  },
]

Answer №1

Imagine you have a data structure set up like this:

[
  {
    productId: '',
    slug: '',
    productType: '',
    title: '',
    description: '',
    teaser_image: '',
    images: '',
    new: '',
    topseller: '',
    brand: '',
  },
  undefined
]

To transform this structure into a more organized array, you can utilize the .filter and .map methods.

const normalizedProducts = allProducts
  .filter(product => product) // filters out falsey values (false, null, undefined, 0)
  .map(product => ({
    productId: product.id,
    slug: product.slug,
    productType: product.product_type,
    title: product.title,
    description: product.description,
    teaser_image: product.teaser_image,
    images: product.images,
    new: product.new,
    topseller: product.topseller,
    brand: product.brand,
  }))

This process will give you the desired output.

Give it a try.

Update:

If there are undefined values within a product object that need to be removed, you can achieve this by converting the object to an array, filtering out the undefined values, and then converting it back to an object using Object.fromEntries() method which is part of ES8 specification.

// sample data
const allProducts = [
  {
    productId: 1,
    slug: 'One',
    productType: 'Two',
    title: undefined,
    description: 'Three',
    teaser_image: 'Four',
    images: 'Five',
    new: undefined,
    topseller: undefined,
    brand: undefined,
  },
]

// handling function
const dataWithoutUndefined = allProducts.map(product => {
  const filteredData = Object.entries(product).filter(([key, value]) => value)
  return Object.fromEntries(filteredData)
})

Check out array.filter documentation

Explore Object.fromEntries documentation

Answer №2

To optimize your code, consider utilizing the map and reduce methods. Begin by creating an array that contains the properties you want to keep, then use the map function on your allProducts array. Ensure that each object returned only includes properties that exist in the original array:

let propertiesToKeep = ["productId", "slug", "productType", "title", "description", "teaser_image",
    "images", "new", "topseller", "brand"];
return allProducts.map(product => {
    return propertiesToKeep.reduce((acc, current) => {
        if (product[current]) { // Check if the property exists in the product
            acc[current] = product[current];
        }
        return acc;
    }, {});
});

Answer №3

If you want to enhance the data in your products array, consider implementing a function to validate each property:


    const allProducts = [
        {
            id: 1,
            title: "Red Shower Head",
            price: 500,
            description: null,
        },
        {
            id: 2,
            title: "JavaScript Course",
            price: 1000,
            description: "Hello World!",
        },
    ];

    function replaceIfInvalid(data, replacementValue) {
        const isValid = checkValidityOfData(data);
        return isValid ? data : replacementValue;
    }

    function checkValidityOfData(data) {
        return data === null || typeof data === "undefined" ? false : true;
    }

    const updatedProducts = [];
    for (let i = 0; i < allProducts.length; i++) {
        const modifiedProduct = {
            productId: replaceIfInvalid(allProducts[i].id, "-"),
            title: replaceIfInvalid(allProducts[i].title, "-"),
            description: replaceIfInvalid(allProducts[i].description, "-"),
            price: replaceIfInvalid(allProducts[i].price, "$$"),
        };
        updatedProducts.push(modifiedProduct);
        console.log(updatedProducts);
    }

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

Managing various dropdown select options in pure JavaScript

Consider the select element provided below: <select multiple="multiple"> <option value="car">car</option> <option value="scooter">scooter</option> <option value="bus">bus</option> </select> I ...

Dragging elements using the jQuery UI Draggable feature onto a designated droppable area

Struggling to implement a Draggable element on Droppable element using jQuery UI? I almost got it working, but the elements on the droppable area keep changing their positions when moved slightly. I want them to stay put, but return to their original place ...

What causes the _.sum() function in lodash to not work with objects in Vuejs?

I've encountered an issue where using Vuejs and Lodash in conjunction with a computed property that calculates the sum of a property in a collection results in unexpected behavior. Instead of summing the values, it seems to concatenate the string [obj ...

Angular8: Stay Updated with Real-Time Data Refreshment

I've implemented code in my app.component to retrieve all users. I'm facing an issue where if I have two windows open and perform any CRUD actions, the second window displays outdated data. To address this, I am attempting to refresh the page ev ...

Is there a way to display the next/previous buttons separately from the scroller in my jQuery thumbnail scroller implementation?

Is there a method to display the next and previous buttons outside of the scroller frame when using jQuery thumbnail scroller by manos.malihu.gr? I have attempted to modify the button class in CSS to make them more prominent or visible, but unfortunately ...

Introducing unnecessary DOM elements when displaying flash messages

When a user saves in my Rails application, it triggers an Ajax request to save the post and then runs the update.js.erb file. This file contains some jQuery code: $('body').append('<div class="message">Saved</div>'); Due t ...

Why won't my picture track the movement of the cursor?

I am trying to make my image follow the cursor using a specific code, but it doesn't seem to be working. I'm having trouble figuring out what's wrong with it. Here is the code snippet that I'm currently using: function followIt(e) ...

Utilize the client-side JavaScript file with ejs framework

Recently, I have been working on creating a website using Express and EJS. I discovered that using just one JavaScript file for all my EJS (view) files was causing issues. If I target a DOM element in one view page and it doesn't exist in another, I w ...

How can you ensure a form is properly validated using javascript before utilizing ajax to submit it

I've been working on developing a website and I am in need of an attractive login/registration/forgot password form. My aim was to utilize 'ajax' to enhance the user experience, leading me to immerse myself in a steep learning curve for the ...

Different boolean variable assigned to every item in v-for loop

I am working on creating a custom play/pause button for my audio elements, and here is how I have implemented it: <div v-for="(post, p) in post_list"> <!-- ... --> <!-- ... --> <!-- ... --> <v-avatar v-i ...

Is the treatment of __proto__ different in the fetch API compared to manual assignment?

When using fetch to retrieve a payload containing a __proto__, it seems that the Object prototype is not affected in the same way as when directly assigning to an object. This behavior is beneficial as it ensures that the Object prototype remains unaffect ...

"Troubleshooting: Resolving 404 Errors with JavaScript and CSS Files in a Vue.js and Node.js Application Deploy

I successfully developed a Vue.js + Node.js application on my local server. However, upon deploying it to a live server, I am facing a 404 error for the JavaScript and CSS files. I have double-checked that the files are indeed in the correct directories on ...

The function signature '(newValue: DateRange<dateFns>) => void' does not match the expected type '(date: DateRange<unknown>, keyboardInputValue?: string | undefined) => void' as per TypeScript rules

I'm currently utilizing the MUI date range picker from https://mui.com/x/react-date-pickers/date-range-picker/. Here's my code snippet: <StaticDateRangePickerStyled displayStaticWrapperAs="desktop" value={valu ...

What is the best way to interpret the final yaml configuration file on Vue pages?

I'm currently working with nuxt and utilizing a config.yml along with an extended file .config.yml. I need to be able to access the final generated config on any page. Is there a way to achieve this? Adding const config = require('config-yml&apo ...

Importing dynamic components on-the-fly in Vue version 2.7

Let me start by clarifying that I am currently working within a Vue 2.7 codebase powered by webpack. This means that any solutions related to Vue 3 or Vite will not be applicable in my case. I am in the process of revamping an old navbar that is generated ...

Rewrite: "Rewriting URL POST requests in Node.js

Within my JavaScript file, I have this function: exports.authentication = function(req, res) { // .. // user validation // .. res.redirect('/login'); }; I'm looking to modify all POST requests to a different path, such as / ...

Using Vue JS to showcase array data in a dropdown menu with Bootstrap-vue

Currently, I have an array of JSON data structured like this: loggers = [{ "allAvailableLevel": ['WARN', 'DEBUG', 'INFO'], "level": "WARN", "logger": "com.test1", "status": "success" }, { ...

An interesting approach to utilizing toggle functionality in JQuery is by incorporating a feature that automatically closes the div when

Currently, I am utilizing JQuery's toggle function to slide a ul li element. However, my desired functionality is for the div to close if someone clicks outside of it (anywhere on the page) while it is in the toggle Down condition. Below, you'll ...

How can you refresh a single element within an array using Angular.js?

System Background: The application is developed using Angular for the front end with routing capabilities, and Node.js, Express, MongoDB, and Mongoose for the back end. Within a controller, there is an array named $scope.array=[]; that is populated throug ...

Fetching images stored on an external website and loading them into an iframe within an Electron application

I am contemplating turning my website into a desktop application using either an iframe or webview within an Electron app. My website contains numerous images that I wish to cache in the Electron app to prevent repeated downloads. Is it possible to access ...