-5

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!

mayerga
  • 23
  • 3
  • read this maybe [MDN on objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) – Jarne Kompier Aug 01 '22 at 11:39
  • Maybe you can use `dataObj.cars[dataObj.cars.length - 1].color.color = "red";` it will work fine if you always got an object of data in last subobject – Mohamed EL-Gendy Aug 01 '22 at 11:42
  • Welcome to SO. You might find reading the site [help section](https://stackoverflow.com/help) useful when it comes to [asking a good question](https://stackoverflow.com/help/how-to-ask), and this [question checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist). _Code that you have worked on to solve the problem should include a [mcve], and be included in your question._ – Andy Aug 01 '22 at 11:43

2 Answers2

0

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);
0

This will use the color of the inner object if applicable otherwise just the color.

yourObject["cars"].forEach(e=>e.color = e.color.color ?? e.color);
soupy-norman
  • 403
  • 2
  • 11