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

What prevents variables defined in outer blocks from being accessed by nested describe() blocks?

In my real code, I encountered a problem that I wanted to demonstrate with a simple example. The code below functions properly. I defined a variable in the root describe() block that can be accessed in the it() blocks of nested describe()s. describe(&apo ...

Using JavaScript to enhance and highlight specific items in a dropdown menu

I am looking for a solution to prevent duplicate selections in multiple select dropdowns. I want to alert the user if they have chosen the same value in more than one dropdown. Should I assign different IDs to each dropdown or is it possible to use just on ...

Adding a nested data structure in a Meteor application

In my mongo collection, I have a document named exam. // meteor:PRIMARY> db.exam.find() { "_id" : "RLvWTcsrbRXJeTqdB", "examschoolid" : "5FF2JRddZdtTHuwkx", "examsubjects" : [ { "subject" : "Z4eLrwGwqG4pw4HKX" }, ...

Type in "Date" and select a date using your mobile device

Hey, does anyone know a good solution for adding placeholder text to an input with type="date"? I'm looking for a way to utilize the phone's built-in date selection feature on a website, rather than having users manually enter dates using the ke ...

It appears that using JQuery's .when and .done functions may result in the code executing before the script has finished loading

Since updating the hard-coded <script> with JQuery promises, I have been encountering these errors frequently: https://i.stack.imgur.com/xkWAk.png The issue seems to be inconsistent in replicating. Sometimes, the error occurs while loading the page ...

Dealing with JavaScript errors within an Express application

Consider the following async function export async function fetchData() { const result = await fetchData(); return result[0].id; } In the route, there is router.post( '/some-route', handleAsyncError(async (req: Request, resp: Response, _ ...

Converting a Class Component to a Functional Component in React: A Step-by-Step

I need to refactor this class-based component into a functional component class Main extends Components{ constructor(){ super() this.state = { posts:[ { id:"0", description:"abc", imageLink: ...

What is the best way to focus on a particular version of TypeScript?

After upgrading my Angular 2 project to RC1 and the router to v3 alpha3, I encountered the following errors: node_modules/@angular/router/directives/router_outlet.d.ts(10,14): error TS1005: '=' expected. It appears to be a TypeScript version is ...

Ways to protect Ajax link requests

Picture this scenario: a user is trying to register on a website and is filling out a form. As the user fills in the form, jQuery continuously validates fields using regular expressions, checks if they are valid, etc. The email address serves as the prima ...

Error: Morris.js is unable to access the property 'x' because it is undefined

Seeking assistance in utilizing Morris.js to create an area chart using data from a JSON file. The JSON data is as follows: [{"period": 0, "time": 121.0}, {"period": 1, "time": 102.0}, {"period": 2, "time": 104.0}, {"period": 3, "time": 91.0}, {"period": ...

Executing a JavaScript function to trigger a PHP script that saves data into a MySQL database

I have a button in my HTML file that, when clicked, should insert data into a database and then reload the page. I am calling a JavaScript function within the onclick event to handle this. Below is the JavaScript function: function grandFinale() { i ...

Changing an array in PHP to a variable in JavaScript

I am struggling with converting a PHP array into a JavaScript variable using json_encode. When I print out my PHP variable: <?php $damage_array = $listing->tire_detail->damage_details; ?> It displays as: Array ( [lf] => 4 [rf] => 9 [lr ...

The curious behavior of JavaScript object fields in Chrome

Attempting to update the targetRow's field with a variable converted from a string to a number is resulting in strange output in Chrome's console: targetRow[fieldName] = Number(value); console.log(targetRow[fieldName]); // = ...

The Angular service encounters issues when interacting with REST API

Within my application, a template is utilized: <div class="skills-filter-input" ng-class="{'hidden-xs': skillsFilterHidden}"> <input type="text" ng-model="skillQuery" ng-change="filterSkills()" placeholder="Filter skills" class="filter- ...

I possess a list of unique identifiers and require the ability to either update an existing object within an array contained in a MongoDB document, if it exists,

I am facing a challenge in updating a specific element within an array in a MongoDB document. I have multiple IDs of that array and need to update the matching element using those IDs. data= [ { "planId" : "plan_FVNvrmjWT7fRDY", "startTime": ...

What is the best way to calculate the sum of table data with a specific class using jQuery?

If I had a table like this: <table class="table questions"> <tr> <td class="someClass">Some data</td> <td class="someOtherclass">Some data</td> </tr> <tr> <td class="s ...

Tips for concealing overlay when the cursor hovers

Can anyone help me with a code issue I'm having? I want to hide an overlay after mouse hover, but currently it remains active until I remove the mouse from the image. Here is the code: .upper {position: absolute; top: 50%; bottom: 0; left: 50%; tra ...

Is the Inline Partial<T> object still throwing errors about a missing field?

I recently updated to TypeScript version ~3.1.6 and defined an interface called Shop as follows: export interface Shop { readonly displayName: string; name: string; city: string; } In this interface, the property displayName is set by the backend a ...

What might be causing the issue in the build process of my next.js project?

**Why is my Node.js YAML file causing an error?** name: Node.js CI on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest strategy: matrix: node-ver ...

Selenium: The function moveToElement is not valid for the driver.actions() method

After creating all my tests using Selenium IDE, I decided to export them to JavaScript Mocha for running in travis. While the tests run smoothly in Selenium IDE and can be exported, I encountered an issue when trying to run them which resulted in the erro ...