Issue
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.
Solution
I think you are looking for something like this:
function cutCarsDescription(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)
}
}
}
}
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
Answered By - miliereya
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.