Is it possible to apply JavaScript object destructuring but make changes to certain values before assigning them to a new object?

After receiving movie data from an api, I am currently manually creating a new object with a subset of properties and modified values. Is there a more efficient way to achieve this using javascript/typescript object destructuring syntax?

I specifically want to use some existing properties like title and overview, but need to change the value of poster_path property. Can this be done in a concise manner?

movieCollection.results.forEach(
      (movie: {
        poster_path: string,
        backdrop_path: string,
        title: string,
        overview: string,
        release_date: string,
        vote_average: number,
        vote_count: number,
        genre_ids: number[],
       }) => {

        if (movie.backdrop_path) {

          //create paths for pictures
          let poster_path = this.secureBaseURL + this.posterSizes[4] + movie.poster_path;
          let backdrop_path = this.secureBaseURL + this.posterSizes[5] + movie.backdrop_path;

          //create array object
          movieArray.push({
            poster_path: poster_path,
            backdrop_path: backdrop_path,
            title: movie.title,
            overview: movie.overview,
            release_date: movie.release_date,
            vote_average: movie.vote_average,
            vote_count: movie.vote_count,
            genre_ids: movie.genre_ids,
            styles: {},
          });
        }
      });

Answer №1

To efficiently achieve the same result, I recommend utilizing Spread syntax. This feature allows an object expression to be expanded in places where key-value pairs are expected, resulting in your objects being included in the new array.

movieCollection.results.forEach(
  (movie: {
    poster_path: string,
    backdrop_path: string,
    title: string,
    overview: string,
    release_date: string,
    vote_average: number,
    vote_count: number,
    genre_ids: number[],
  }) => {
    if (movie.backdrop_path) {
      //create array object
      movieArray.push({
        ...movie, // preserving unchanged properties
        poster_path: this.secureBaseURL + this.posterSizes[4] + movie.poster_path,
        backdrop_path: this.secureBaseURL + this.posterSizes[5] + movie.backdrop_path, // updating these two properties as required
        styles: {},
      });
    }
  });

It appears that you intend to modify objects in an array and store the updated results in another array. In this case, using Array map can help streamline your code effectively.

const movieArray = movieCollection.results
  .filter((t) => !!t.backdrop_path) // filtering based on backdrop_path property
  .map(
    (movie) => ({
      ...movie, // keeping original properties
      poster_path: this.secureBaseURL + this.posterSizes[4] + movie.poster_path,
      backdrop_path: this.secureBaseURL + this.posterSizes[5] + movie.backdrop_path,
      styles: {},
    }),
  );

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

Function used to update database through AJAX technology

I have implemented a PHP script to update my database using AJAX, and it is working correctly after being tested. To pass the required two variables to the PHP script for updating the database, I created a JavaScript function that utilizes AJAX to call the ...

Prevent redirection on buttons within ionic lists

THE ISSUE: I am facing an issue in my Ionic app where I am using the ion-list component. Each item in the list can be swiped to reveal a button (add/remove to favorites). Additionally, each item serves as a link to another page. The problem arises when ...

Issue detected in TypeScript code - "Could not locate property 'setSelectedFile' in type 'void'.ts(2339)"

Encountering a TypeScript error in my code and seeking assistance. Below are the codes of 2 files with the error message included for review. The file causing the error is named "NewPostForm.tsx". import React, { useState } from 'react&apos ...

Performing an AJAX request to send data containing special characters

What is the best way to send a large string with special characters like '%' and '&' to my PHP page using AJAX POST? In simple terms, how can I encode these characters in JavaScript and then decode them in PHP? ...

Modifying the name of a file upload in AngularJS

Does anyone know a way to dynamically change the file name in AngularJS? <input type="file" onchange="angular.element(this).scope().filename(this)"> In the filename method, I am attempting to change the file name but the value is not updating. How ...

I have a quick question: What is the most effective method for creating PDF templates with Angular and .NET 6, specifically for designs that feature heavy

Seeking the optimal solution for creating PDF templates using Angular and .NET 6? Specifically looking to design templates that heavily feature tables. In my exploration of efficient PDF template creation with Angular and .NET 6, I ventured into using pdf ...

What steps can be taken to address the error "console is undefined" in PowerShell?

I have a basic .js file saved on one of my drives that contains the following code: var x=3; function numSqaure(x) { return(x*x); } var sentence="The square of" + x + "is" + numSqaure(x); console.log(sentence); When attempting to run this script thro ...

For each array element that is pushed, create and return an empty object

I am encountering an issue with an array where the objects are being generated by a push operation within a function. Despite successfully viewing the objects directly in the array, when I attempt to use forEach to count how many times each id uses the ser ...

typescript function intersection types

Encountering challenges with TypeScript, I came across the following simple example: type g = 1 & 2 // never type h = ((x: 1) => 0) & ((x: 2) => 0) // why h not never type i = ((x: 1 & 2) => 0)// why x not never The puzzling part is w ...

Animating Angular ng-template on open/close state status

I am looking to add animation when the status of my ng-template changes, but I am unable to find any information about this component... This is the code in my report.component.html <ngb-accordion (click)="arrowRotation(i)" (panelChange)="isOpen($even ...

What is the best way to select multiple items using mongoose?

For instance, consider this list: [ { name: "John" }, { name: "Mike" }, { name: "Homer" }, { name: "Bart" }, { name: "Dmitry" }, { name: "Dan" } ] If I want to select specific objects ...

Dealing with validations in a personalized aid

Recently, I've been exploring CodeceptJs and have found it quite easy to work with. Currently, I'm utilizing it with NightmareJs for testing a gallery that retrieves data from an interface via JSONP to create a list of images enclosed in <div& ...

What are some solutions for troubleshooting a laptop freeze when running JavaScript yarn tests?

Running the yarn test command results in all 20 CPU cores being fully occupied by Node.js, causing my laptop to freeze up. This issue is particularly troubling as many NodeJS/Electron apps such as Skype, MS Teams, and Slack are killed by the operating syst ...

Switch over to TypeScript - combining Socket.IO, Angular, and Node.js

This is the code I'm using for my node server: import http from 'http'; import Debug from 'debug'; import socketio, { Server } from 'socket.io'; import app from './app'; import ServerGlobal from './serve ...

Tips for embedding a file within a text box in HTML and enabling users to make direct edits

I am currently working on a feature that allows users to open a .txt or .html file from their file explorer and paste the contents into a textarea for editing and saving purposes. My question is whether it's possible to read the file content and auto ...

Creating a personal TypeScript language service extension in Visual Studio Code

Currently, I am working on developing a TSserver plugin in VSCode and struggling to get the server to load my plugin. I have experimented with setting the path in tsconfig.json to both a local path and a path to node_modules, but it still isn't worki ...

React SlideMenu will not close when a link is clicked

I am facing an issue with my off-canvas menu, which slides in when the variable isOpen is set to true. However, the problem arises when trying to slide it back out upon clicking a Link to navigate to another page. Instead of sliding out, the mobile menu oc ...

What tips can you provide for shrinking the size of an AngularJS website with the help of Google Closure Compiler?

Is there a way to decrease the size of an Angularjs site using Google Closure Compiler? I have a website built on Angularjs 1.8.x and I am interested in compiling it with Closure. Are there any examples or demonstrations available to help me achieve this ...

Traversing a JavaScript class within a for loop

I am attempting to access the locations listed in json.responseJSON.Sites, starting with LHR on the first iteration and then NJE on the next one, and so forth. The notifications for each location are "LHR" and "NJE", respectively. Is it possible to achieve ...

Find all the different ways that substrings can be combined in an array

If I have a string input such as "auto encoder" and an array of strings const arr = ['autoencoder', 'auto-encoder', 'autoencoder'] I am looking to find a way for the input string to match with all three values in the array. ...