I would like to know if there is a way to access the "description" property of the objects within the array and use some string cutting method, such as slice, returning an array of objects with the value of this property already modified. I tried with some for loops but I didn’t get the result.
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 get the property I want and use slice() inside a for loop to cut it, but I’m having difficulty returning this array of objects when i call "carsTwo" with the information already modified. Here’s what i’ve done:
let carsTwo= cars[1].models;
//here i'm deleting the propreties that i don't want to return in my new array
for(let i=0; i<carsTwo.length; i++) {
delete carsTwo[i].color;
delete carsTwo[i].price;
}
//here i'm trying to apply slice() in every "description" property value, and it works but only in console.log...
for(let i=0; i<carsTwo.length; i++) {
carsTwo[i].description.slice(3)
}
my goal is to return the array of objects only containing description property, with the slice applied.
obs: i’m a beginner.
3
Answers
I think you are looking for something like this:
Just path cars as the 1st argument and index of slicing as the 2nd
It will modify your cars array, so you don’t need to return anything from function
.slice()
returns the new string, it doesn’t modify the string in place, so you’d need to update your.description
property on the object to assign it to the new string thatslice()
returns:Note the above about your code above:
You have two
for
loops one after another that both loop the same amount of times. These should be merged together to avoid doing an additional iteration of your items:By using operations such as
delete
and updating the original object by reassigning.description
, you’re updating the objects in your original array, which may not be desirable (you can see this if you print yourcars
array after the above code).To avoid updating your original array, I would suggest creating a new array and adding new objects with the
description
property instead of modifying your existing array of objects. This can be done by using.map()
to transform each object in yourmodels
array to a new array of objects, that way you’re not updating the original objects, keeping the originalcars
array untouched:It is possible to do in a quite concise manner by using Array.map():