Steps to convert a subelement into a string

I am looking to update the value of a specific key in each object within an array as new objects are dynamically added.

Why?

My goal is to further my understanding of array methods and JSON manipulation.

To progress, I posed myself this question: How can I change the value of a key in every object within an array?

Here is the initial data structure:

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

My objective is to replace the color value in the last subobject with "yellow" dynamically. How can I achieve this?

The desired outcome should look like this:

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

Thank you!

Answer №1

const carsData = {
    "cars" : [
        {
            "id": 0,
            "color": "blue"
        }, 
        {
            "id": 3,
            "color": "-"
        },
        {
            "id": 0,
            "color": {
                    "id": 0,
                    "color": "yellow"
            }
        }
    ]
};
carsData.cars = carsData.cars.map(vehicle => { vehicle.color = typeof vehicle.color === "string" ? vehicle.color : vehicle.color.color; return vehicle; })

console.log(carsData);

Answer №2

The inner object's color will be used if available, otherwise the default color will be used.

yourObject["cars"].forEach(car=>car.color = car.color.color ?? car.color);

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

Emotion, material-ui, and typescript may lead to excessively deep type instantiation that could potentially be infinite

I encountered an issue when styling a component imported from the Material-UI library using the styled API (@emotion/styled). Error:(19, 5) TS2589: Type instantiation is excessively deep and possibly infinite. Despite attempting to downgrade to typescript ...

Set the background-color of each <td> element to be equal to a value in the array, with each group of three elements having the same

I am trying to color every <td> element in a row of three columns with the same color using the following code: for (var i = 0; itr < $("td").length; i++) { $("td").eq(i).css("background-color", Colors[i]); } However, this code colors each i ...

A guide to navigating a JSON array

Utilizing node js, I have extracted the following array by parsing through multiple json files to find a specific value. My json files consist of a collection of IDs with their respective status: isAvailable or undefined. https://i.sstatic.net/AlpVk.png ...

Ensure that the promise is fulfilled only if a specific condition is met

I have a complex if-else condition in my code that includes different promises. Once the logic determines which condition to enter and executes the corresponding promise, I need to ensure that a final promise is always executed. if (a < 5) { vm.pr ...

Is the length of the Java array negative?

While reviewing code in an open source project, I encountered a method related to output streams that looks like the following: @Override public void write(byte[] buffer, int offset, int length) { if (buffer == null) { throw new NullPointerExc ...

Is there a way I can detect a browser timeout and display a custom error message?

My webpage in classic asp contains a link to a local IP address, shown below: <a href="http://192.168.1.89">Link</a> When the local IP address is not available, the web browser eventually times out and shows its own error message. I ...

Ways to detect when the window printing process has been completed

Within my application, I attempted to generate a voucher page for the user using the following code: var htm ="<div>Voucher Details</div>"; $('#divprint').html(htm); window.setTimeout('window.print()',2000); The &apo ...

Update a particular package using Node

Is there a way to update Browser-sync without updating all my node packages? I need the version with the Browser-sync GUI, but I don't want to update everything else. ├─┬ <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

Tutorial on creating a subset of a series using jqplot

I am looking to display three series on the same canvas. The series are defined as follows: rec1 = [0, 0, 150, 200, 0 ]; rec2 = [60, 120, 179, 240, 300]; rec3 = [50, 100, 150, 200, 250]; Below are the source codes I am using to draw these series. $ ...

react validation for dropdown, react-datepicker, and hour input at intermittent intervals

I have integrated the following packages into my project :- react-datepicker library for selecting from time and to time date validation with date-fns, moment.js, additional validations using jQuery and lodash libraries/packages If you want to view my pr ...

Struggles encountered while configuring React

I'm in need of assistance with setting up React, even though I have both Node and npm installed. When I enter the following command: npx create-react-app new-test-react --use-npm I encounter the following error message: npm ERR! code ENOTFOUND npm E ...

Tips for managing cross-referencing visibility between two distinct div elements using AngularJS

Currently, I am working on an AngularJS project and facing a specific issue that I need help with. I have two div elements to deal with. The first div contains a list of images as anchors which are generated using the ngRepeat directive. The second div s ...

Unable to install vue-property-decorator

When attempting to set up Vue and TypeScript with class style using vue-property-decorator, I encountered a strange script after creating the project. I was anticipating a script like this: <script lang="ts"> import {Component, Vue} from & ...

Adjust the orientation of a Three.js-generated 3D "Cube" to create a new view

I've managed to create a 3D wire-frame cube using Three.js examples, but I'm looking to adjust the cube's angle. Currently, it appears like this: However, I want it to resemble this: Take a look at my code: HTML <script src="http://w ...

Accessing Google Feed API to retrieve media thumbnails

I am currently utilizing the Google Feed API to extract a thumbnail from an RSS feed ("media:thumbnail") The media:thumbnail element in the RSS feed is structured as follows: <media:thumbnail url="http://anyurl.com/thumbnailname.jpg" width="150" heigh ...

How can we efficiently generate ReactJS Router for Links and seamlessly display a unique page for each Link?

Currently, I have an array of objects named titleUrl, which contains titles and URLs retrieved from an API. To display these as links on the sidebar, I am utilizing a custom component called MenuLink. The links are generated by iterating over the keys in t ...

Package.json failing to enable NodeJS unsafe-perm functionality

Attempting to execute a npm install command with a preinstall script in my package.json. Despite being aware of it being considered an antipattern, I need to run certain scripts as root. The approach works when adding a .npmrc file with the content unsafe ...

What sets Babel and TypeScript apart from each other in terms of functionality and features?

While TypeScript was utilized to create Angular2, Babel also appears quite similar. Many established companies prefer Babel over TypeScript. Here are some questions to consider: What specific advantages does each one offer? Which is a better or worse ch ...

Exploring the variable scope in Node.js with a focus on separating routes

My routing configurations are stored in an external folder. Find them in the ./routes directory This is how I set up my routes within the server.js file: app.get('/', routes.index); app.post('/validation', register.valid); The reg ...

Is it possible to set all UI forms to a readonly/disable mode?

We have a specific requirement where, if the user's access level is set to "READ ONLY", all form input elements should be made readonly. Our coding approach involves using a template HTML that contains widgets which are referenced in the correspondin ...