What is the best way to trim a string property of an object within an array?

I am seeking a solution to access the "description" property of objects within an array and utilize a string cutting method, such as slice, in order to return an array of modified objects. I have attempted using for loops but have been unsuccessful.

Here is the code:

let cars = [
  {
    "status": "disabled"
  },
  
  {
    "status": "active",
    "store": true,
    "models": [
        {
          "description": "4 doors, 0km/h, no breakdowns",
          "color": "black",
          "price": 100.000,
        },
        {
          "description": "2 doors, 30.000km/h, some breakdowns",
          "color": "black",
          "price": 20.000,
        },
      
        {
          "description": "4 doors, 120.000km/h, no breakdowns",
          "color": "red",
          "price": 50.000,
        }
    ]
  }
]

I can extract the desired property and use slice() within a loop to modify it, however I am struggling with returning this updated array of objects when calling "carsTwo". Here is what I have tried:

let carsTwo= cars[1].models;

//remove unwanted properties from new array
for(let i=0; i<carsTwo.length; i++) {
    delete carsTwo[i].color;
    delete carsTwo[i].price;
}

//apply slice() to every "description" property value, successfully displayed in console.log...
for(let i=0; i<carsTwo.length; i++) {
    carsTwo[i].description.slice(3)
}

My objective is to return the array of objects containing only the description property, with slice applied.

Note: I am a beginner in programming.

Answer №1

.slice() will return a new string instead of modifying the existing string. To update the .description property in the object, you need to assign it to the new string returned by slice():

carsTwo[i].description = carsTwo[i].description.slice(3);

const cars = [
  {
    "status": "disabled"
  },
  
  {
    "status": "active",
    "store": true,
    "models": [
        {
          "description": "4 doors, 0km/h, no breakdowns",
          "color": "black",
          "price": 100.000,
        },
        {
          "description": "2 doors, 30.000km/h, some breakdowns",
          "color": "black",
          "price": 20.000,
        },
      
        {
          "description": "4 doors, 120.000km/h, no breakdowns",
          "color": "red",
          "price": 50.000,
        }
    ]
  }
];

const carsTwo = cars[1].models;

for(let i=0; i<carsTwo.length; i++) {
    delete carsTwo[i].color;
    delete carsTwo[i].price;
}

for(let i=0; i < carsTwo.length; i++) {
    carsTwo[i].description = carsTwo[i].description.slice(3);
}

console.log(carsTwo);

Take note of the following regarding your current code:

  • You have two consecutive for loops that iterate over the same items. It is recommended to combine them into one loop to avoid unnecessary iterations:

    for(let i=0; i<carsTwo.length; i++) {
      delete carsTwo[i].color;
      delete carsTwo[i].price;
      carsTwo[i].description = carsTwo[i].description.slice(3);
    }
    
  • When using delete and reassigning .description, you are modifying the original objects in the array. This may not be desired if you wish to keep the original array intact.


To prevent altering the original array, consider creating a new array and adding new objects with the description property without modifying the existing objects. This can be achieved by utilizing .map() to transform each object in the models array into a new array of objects, preserving the original cars array:

const cars = [ { "status": "disabled" }, { "status": "active", "store": true, "models": [ { "description": "4 doors, 0km/h, no breakdowns", "color": "black", "price": 100.000, }, { "description": "2 doors, 30.000km/h, some breakdowns", "color": "black", "price": 20.000, }, { "description": "4 doors, 120.000km/h, no breakdowns", "color": "red", "price": 50.000, } ] } ];

// Using destructuring assignment to extract the models array from the second object in your array
// Alternatively, you can use: `const models = cars[1].models` to achieve the same result as the line below.
const [, { models }] = cars;

const res = models.map((model) => ({description: model.description.slice(3)}));
console.log(res);

Answer №2

Here's a function I believe suits your needs:

const truncateCarDescription = (cars, index) => {
    for(let i = 0; i < cars.length; i++) {
        const car = cars[i]
        if(car.models) {
            for(let j = 0; j < car.models.length; j++) {
                const model = car.models[j]

                model.description = model.description.slice(0, index)
            }
        }
    }
}

Simply pass in the cars array as the first argument and the desired index of slicing as the second.

This function will directly modify the cars array without needing to return anything.

Answer №3

One way to achieve this efficiently is by utilizing the Array.map() method:

const cars = [ { "status": "disabled" }, { "status": "active", "store": true, "models": [ { "description": "4 doors, 0km/h, no breakdowns", "color": "black", "price": 100.000, }, { "description": "2 doors, 30.000km/h, some breakdowns", "color": "black", "price": 20.000, }, { "description": "4 doors, 120.000km/h, no breakdowns", "color": "red", "price": 50.000, } ] } ];
const carsTwoModified = cars[1].models.map((model) => ({ description: model.description.slice(3) }));

console.log(carsTwoModified);

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

Utilizing AJAX in jQuery Mobile for Collapsible Content

I am currently generating a variable number of these elements using a foreach() loop: <div id="<?php echo $data['id']; ?>" data-role="collapsible" data-theme="a"> <h1 style="white-space: normal"><?php echo $data['te ...

Generate and save a document

Upon clicking the button, I am trying to generate a CSV file and download it right away. My current approach is as follows: html: <a class="btn btn-primary" @click="downloadCsv">Download CSV</a> <a v-if="fileObjectUrl !== null" ref="down ...

Divide a list Observable into two parts

In my code, I have an Observable called 'allItems$' which fetches an array of Items. The Items[] array looks something like this: [false, false, true, false] My goal is to split the 'allItems$' Observable into two separate Observables ...

When the user signs in with Next-auth, they will be redirected to /signin with

After following the documentation to implement next-auth, I encountered an issue. When I visit http://localhost:3001/api/auth/signin, I see a page with a link (https://i.stack.imgur.com/xb0fx.png) but clicking "signin with Google or GitHub" just refreshes ...

Angular 2- Unable to bind to 'ngSwitchCase' as it is not recognized as a native property

I am facing an issue with my code where I have two lists that are displayed in my .html file. In order to avoid repetition, I decided to utilize ngSwitch. However, when I try to implement this approach, I encounter an error. Here is the snippet of code cau ...

Finding All Initial Table Cells in jQuery

Is there a streamlined method for retrieving all td elements (cells) from every row within a specific table, or do I have to manually iterate through the collection myself? ...

Operating a React application in the background

Being a novice in the world of deploying front-end code, I have encountered a challenging situation that requires assistance. I am currently working on a React App that needs to be operated as a background process. However, I'm facing some confusion r ...

What is the best way to distinguish between relative blocks and convert them to absolute positioning?

What is the best way to locate relative blocks and convert them to absolute position while keeping them in the same place? Is this something that can be achieved using JavaScript or jQuery, or is it simply not possible? Thank you very much. ...

Determine the variance between two strings using Jquery

Hello and thank you in advance for your help. I'm facing a basic query here - I have two variables: var x = 'abc'; var y = 'ac'; I am looking to compare the two variables and find the dissimilarity between them, which should be: ...

Utilizing JavaScript regex to remove substrings that contain parentheses

I am working with a string variable named myString that includes some unwanted content towards the end: var myString = 'The sentence is good up to here foo (bar1 bar2)'; var toBeRemoved = 'foo (bar1 bar2)'; I am looking for the best w ...

Definition file for Typescript d.ts that includes optional properties in a function

Within my code, I have a function that offers different results based on specified options. These options dictate the type of return value. The function is currently written in plain JavaScript and I am looking to provide it with types using an index.d.ts ...

What is the trick to accessing an object's key and value when you are unsure of the object's

Currently, I am in the process of constructing a React component that is designed to receive an array of objects. However, I have encountered a question: Is there a way for me to retrieve both the key and value of an object within the map function without ...

Refresh cloned element after making changes to the original element

Just starting to explore Jquery and looking for some guidance to get me started :) Question: I'm facing an issue with a cart total price that is displayed in a different part of the page using clone(). I want this cloned price to automatically update ...

Flashing issues when utilizing the Jquery ui slider within an Angular 2 component

I recently incorporated a jquery-ui slider plugin into an angular 2 component and it's been working well overall, but I have encountered an annoying issue. Whenever the slider is used, there is a flickering effect on the screen. Interestingly, when I ...

What is the approach of Angular 2 in managing attributes formatted in camelCase?

Recently, I've been dedicating my time to a personal project centered around web components. In this endeavor, I have been exploring the development of my own data binding library. Progress has been made in creating key functionalities akin to those f ...

Node.js does not allow the extension of the Promise object due to the absence of a base constructor with the required number of type

I'm trying to enhance the Promise object using this code snippet: class MyPromise extends Promise { constructor(executor) { super((resolve, reject) => { return executor(resolve, reject); }); } } But I keep encou ...

Error: Azure AD B2C user login redirect URI is not valid

Currently working on setting up user login with Azure AD B2C. I have successfully created an App Registration in my B2C tenant and specified http://localhost:3000 as the redirect URI. However, when implementing it in my React app using the MSAL React libra ...

Creating a custom theme in MUI v5 by modifying ColorPartial members

I am seeking a solution to override certain members within PaletteOptions. My goal is to switch the type of grey from ColorPartial to PaletteColorOptions in order to include additional members. This was my attempt at implementing the necessary code: decl ...

Modify the bootstrap form dynamically in response to the user's input. Update the form layout instantly as the user types, with no need for clicking any buttons

Imagine a scenario where, as soon as you enter your credit card number, the form automatically undergoes a change without requiring a button click, similar to how a credit card logo pops up. The form detects changes instantly after the input field has be ...

What could be causing the npm install command to not save packages in the /node_modules directory?

After running npm install to add a package, npm indicates that the installation was successful. However, upon checking the node_modules folder, I'm unable to locate the installed package. In order to access the package, I have resorted to using npm in ...