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

Searching for a particular Prettier setting

Seeking a Nicer alternative. I am exploring if there is a way to format code like this without moving the first attribute to a new line: <div class="test-class" [test-binding]="true" (test-binging)="test()" ...

Text randomly appears on the html page

I've been dedicating a significant amount of time to finding a solution, but haven't had any luck. I'm aiming to create a visual effect where 10 words with varying font sizes slide in from different directions on a canvas within my document ...

Generating ChartJS in Real-time

I have a straightforward form where the user selects a start date and an end date. Once these dates are selected, the tool automatically fetches data from a website in JSON format. Below is the code for my Angular controller: (function () { angular.m ...

Modifying the id attribute dynamically using jQuery during runtime

In my project, I have a submit button with the id of "submit" that is used to save new records. // Function to add a new customer record $("#submit").click(function() { var data = $.param($("#form").serializeArray()); ...

Finding the best way to transfer text between DIV elements?

I have a dilemma involving two DIV elements positioned absolutely on the sides of an HTML page, much like this EXAMPLE: <div class="left"> </div> <div class="right"> </div> These are styled using the following CSS: .left{ pos ...

What is the best way to change a byte array into an image using JavaScript?

I need assistance converting a byte array to an image using Javascript for frontend display. I have saved an image into a MySQL database as a blob, and it was first converted to a byte array before storage. When retrieving all table values using a JSON ar ...

Navigate directly to the section on the page that discusses the hashtag

So, I have a unique scenario to address. I'm working with two div elements where only one should be visible at a time. Here's the situation: The first div serves as an introduction page with a button that hides it and reveals the second div. Th ...

Tips for testing Sequelize with Jasmine

In my database/index.ts file, I set up a Sequelize database using the code below: import { Sequelize } from 'sequelize'; const { DATABASE_DIALECT, DATABASE_HOST, DATABASE_PORT, DATABASE_USER_NAME, DATABASE_USER_PASSWORD, DATABASE_NAM ...

The absence of AudioPlayer may be responsible for the compilation failure on Vercel

Here is the latest code snippet import { useState, useEffect, useRef } from "react"; import { FaPlay, FaPause, FaForward, FaBackward } from "react-icons/fa"; export default function Player() { const [isPlaying, setIsPlaying] = useState(false); const [ ...

Encountering issues during the transition to the updated react-native version 0.70 has posed a challenge for

Help! I encountered an error and need assistance fixing it. I've tried clearing my cache but that didn't work! The error is a TypeError: undefined is not a function in the JS engine Hermes. It also shows an Invariant Violation: Failed to call in ...

Safari is not properly handling element IDs when used in conjunction with React

I am currently in the process of building a straightforward single-page website utilizing React. At the top of the page, there is a navigation bar that contains links to various sections of the site: <li><a href="/#about">About u ...

What is the method for getting js_xlsx to include all empty headers while saving the file?

In the midst of developing a Meteor App, I've incorporated the Node.js package known as "js_xlsx" from "SheetJS", produced by "SheetJSDev". This tool enables me to convert an Excel sheet uploaded into JSON on the backend. The intention is to store thi ...

jquery.event.drag - Execute code for each increment of X pixels dragged

Currently, I am utilizing jquery.event.drag.js for a project I am developing. My goal is to execute a script after every interval of X pixels dragged along the X axis. Below is a snippet of the code I have implemented. $('body').drag(function( e ...

Navigating through a diagonal path

Struggling to craft a diagonal navigation system similar to the images below. Despite its seemingly simplicity, I'm stuck investing too much time in figuring it out. My goal is for the menu container to smoothly reveal from right to left when clicking ...

What is causing the unexpected impact of the "Product Quick View" JavaScript plugin on divs that are not being activated by user interaction?

As a newcomer to web design, I have implemented the "Product-Quick-View" plugin from CodyHouse on my website. Upon clicking the DEMO button and inspecting the code, you will find the following: <body> <header> <h1>Product Q ...

Header Blocks that are Fixed While Scrolling in fullPage.js Sections Using the "scrollOverflow: true" Feature

I am experiencing an issue where a fixed header on my website prevents scrolling through sections when hovering, specifically when the setting scrollOverflow: true is enabled. However, everything works fine and scrolling through all sections is possible w ...

Create a new column in Material UI Grid by adding an empty div element instead of using padding

I'm currently getting acquainted with Material UI Grid and I am interested in adding an empty column (a blank space on the right of the first element) without utilizing padding. How can this be achieved? Here's a snippet of the code being discus ...

Is there a way to extract only the value from the most recent request?

While working with VueJS, I have a handler for changes in an input field that looks like this: inputHandler(url, params){ const p = new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('POST&ap ...

Complete interaction with child processes in Node.js

I have a basic C++ program compiled using the command gcc 1.cpp -o 1.exe. // 1.cpp #include <stdio.h> int main(){ int num = 0; scanf("%d", &num); printf("%d", num + 1000); scanf("%d", &num); printf("\n%d", num + 1000); ...

Explore additional sub-categories by clicking on them with the help of jQuery or alternate techniques

I am currently working on a Magento store that has Categories with an overwhelming amount of sub-categories, taking up almost half of the page. I want to enhance user experience by implementing a feature that displays a "Load more" button when there are mo ...