javascriptarraysobjectarrayobject

How to transform subobject into a string


I am trying to change the value of an object key when new objects are added to the array dynamically.

Why?

Because I would like to continue learning array methods and working with JSON.

In order to move forward, I asked myself this question. Change the value of a key in each of the objects of an array.

I have the following:

{
    "cars" : [
        {
            "id": 0,
            "color": "blue"
        }, 
        {
            "id": 3,
            "color": "-"
        },
        {
            "id": 0,
            "color": {
                    "id": 0,
                    "color": "yellow"
            }
        }
    ]
}

I would like to replace the last subobject ("color") with the value "yellow". How could I do it dynamically?

So the solution should be like:

{
        "cars" : [
            {
                "id": 0,
                "color": "blue"
            }, 
            {
                "id": 3,
                "color": "-"
            },
            {
                "id": 0,
                "color": "yellow"
            }
        ]
    }

Thank you!


Solution

  • let dt = {
        "cars" : [
            {
                "id": 0,
                "color": "blue"
            }, 
            {
                "id": 3,
                "color": "-"
            },
            {
                "id": 0,
                "color": {
                        "id": 0,
                        "color": "yellow"
                }
            }
        ]
    };
    dt.cars = dt.cars.map(it=>   { it.color = typeof it.color == "string" ? it.color : it.color.color; return it; } )
    
    console.log(dt);