81-Nodejs Course 2023: Resources: Working With Arrays
Tags: node, typescript, mongodb, fastify
Published: 2022-12-03 07:59:33

---
title: 81-Nodejs Course 2023: Resources: Working With Arrays
published: true
description: 
series: Nodejs Course 2023
tags: nodejs, typescript, mongodb, fastify
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vzlgfw4nck54iz56hsl4.png
# Use a ratio of 100:42 for best results.
---

What if our output contains not only a single value, but an array of values? for example we're returning `images` that holds list of images, how can we return it using `uploadsUrl` function?

This is where our article is going to talk about, arrays of any kind.

## Arrays

The concept here is actually pretty much simple, we'll just make a check if the value is an array, then we'll loop over it and apply on it our transformation functions, otherwise just apply the transformation functions on the value.

But as we're already making multiple checks, like if `valueType` is string then make a built cast, if its a function then call it, and if it is a resource then parse it, so let's group all of these checks in one method so we can call it when the value is just a single value or its an array.

## Transform value

We'll create a new method let's call it `transformValue` which will basically receives two arguments, the value and the value type, and according to the value type we can decide how the value will be transformed.

```ts
// src/core/resources/resource.ts

// ...

  /**
   * Transform value
   */
  protected transformValue(value: any, valueType: any) {
    if (typeof valueType === "string") {
      value = this.cast(value, valueType);
    } else if (valueType.prototype instanceof Resource) {
      value = new valueType(value);
    } else if (typeof valueType === "function") {
      value = valueType.call(this, value);
    }

    return value;
  }
```

This method basically do the exact same thing we did earlier, but we just moved it in a separate method.

> You may notice that the `valueType` if it is a function, i updated it to use `call` just to bind the resource object to it as `this`, this can be useful if the value type function is related to current resource class.

Now let's update our `toJSON` method to use this new method.

```ts
// src/core/resources/resource.ts

// ...

/**
 * {@inheritDoc}
 */
    public toJSON() {
        // final output
        const data: Record<string, any> = {};

        // loop through the output property
        for (const key in this.output) {
            // get the value type
            const valueType = this.output[key];
            // get the value, and also make sure to skip the output property if it is missing from the given resource
            let value = get(this.resource, key, missingKey);

            // skip the output property if it is missing from the given resource
            if (value === missingKey) {
                continue;
            }

            // just for now sett the output value to the data
            data[key] = this.transformValue(value, valueType);
        }

        return data;
    }
```

We replaced our code to use the new method `transformValue`, this will firstly make our code cleaner, and also allows us to use the method when the value is an array.

```ts
// src/core/resources/resource.ts

// ...


/**
 * {@inheritDoc}
 */
    public toJSON() {
        // final output
        const data: Record<string, any> = {};

        // loop through the output property
        for (const key in this.output) {
            // get the value type
            const valueType = this.output[key];
            // get the value, and also make sure to skip the output property if it is missing from the given resource
            let value = get(this.resource, key, missingKey);

            // skip the output property if it is missing from the given resource
            if (value === missingKey) {
                continue;
            }

            // check if value is an array
            if (Array.isArray(value)) {
                value = value.map((item) => this.transformValue(item, valueType));
            } else {
                // transform single value
                value = this.transformValue(value, valueType);
            }
        }

        return data;
    }
```

And that's it, now we can pass a list of values or single value, doesn't matter it will always be transformed accordingly.

## 🎨 Conclusion

We did two things here in this article, we created a new method `transformValue` which will transform a single value, and we also updated our `toJSON` method to use this new method, and also to check if the value is an array, if it is then we'll loop over it and apply the transformation on each item.

## ☕♨️ Buy me a Coffee ♨️☕

If you enjoy my articles and see it useful to you, you may [buy me a coffee](https://www.paypal.com/paypalme/hassanzohdy), it will help me to keep going and keep creating more content.

## 🚀 Project Repository

You can find the latest updates of this project on [Github](https://github.com/hassanzohdy/nodejs-2023)

## 😍 Join our community

Join our community on [Discord](https://discord.gg/pb2vmdfhGf) to get help and support (Node Js 2023 Channel).

## 🎞️ Video Course (Arabic Voice)

If you want to learn this course in video format, you can find it on [Youtube](https://www.youtube.com/playlist?list=PLGO8ntvxgiZMJc7RN2lIq9WmMOlWZGzmz), the course is in Arabic language.

## 📚 Bonus Content 📚

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

* [Event Driven Architecture: A Practical Guide in Javascript](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
* [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
* [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)

Packages & Libraries

* [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
* [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
* [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)

 React Js Packages

* [useFetcher: easiest way to fetch data in React Js](https://dev.to/hassanzohdy/usefetcher-the-easiest-way-to-fetch-data-in-react-45o9)

Courses (Articles)

* [OOP In JS And TS From The Very Beginning](https://dev.to/hassanzohdy/jsts-oop-course-1-introduction-2ld)
* [ES6++: The Ultimate Guide to ES6 and Beyond](https://dev.to/hassanzohdy/es6-1-introduction-h3e)
* [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)