updating an element within an array without needing to stringify the array using JavaScript in Google Apps Script

Utilizing app script to retrieve data from an API and convert it into JSON format.

var data = UrlFetchApp.fetch(***);
var obj = JSON.parse(data); // Convert to JSON
Logger.log(typeof(obj)); // Returns object type

Here is an example of the returned JSON array:

var dataJson = [{age=20, gender=female, country=usa, name=sali, type=female},{age=25, gender=male, country=usa, name=john, type=female},{age=19, gender=female, country=usa, name=anita, type=female},{age=22, gender=male, country=usa, name=fredo, type=female}]

If gender is female, change the country to UK. If gender is male, change the country to Canada.

After updating the array, ensure that 'type' remains as an object, not a string.

The updated result would be:

[{age=20, gender=female, country=uk, name=sali, type=female},{age=25, gender=male, country=canada, name=john, type=female},{age=19, gender=female, country=uk, name=anita, type=female},{age=22, gender=male, country=canada, name=fredo, type=female}]

Please note: the data is dynamic and subject to change.

Answer №1

If you want to transform the data, one option is to use the map function.

var dataJson = [{age:20, gender:'female', country:'usa', name:'sali', type:'female'},{age:25, gender:'male', country:'usa', name:'john', type:'male'}]


const result = dataJson.map(({gender, ...rest}) => {
const isFemale = gender === 'female'
 return {
   ...rest,
   gender: isFemale? 'woman': 'man',
   country: isFemale ?'uk': 'canada'
 }
})

console.log(result)

Answer №2

Is your sole purpose to find:

dataJson = dataJson.map(item => {
    if(item.gender === 'female'){
        item.country = 'uk'
    }
    if(item.gender === 'male'){
        item.country = 'canada'
    }
    return item
})

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

Protractor: Moving further down the page

One issue I encountered is with a button on my page that becomes visible only when the user scrolls down. As a result, Protractor tests are throwing an error: UnknownError: unknown error: Element is not clickable at point (94, 188). I attempted to reso ...

Tips on enabling JS tooltips in Shadow DOM

I am currently developing an app using Vue and Bootstrap, where I am creating web components based on the official Vue documentation. The Bootstrap framework and my business logic are functioning well within the #shadow-root of the web components, behaving ...

You can definitely invoke a function within a React hook

This code snippet showcases a component utilizing Hooks in React Native import React, { useEffect, useState } from 'react'; import { StyleSheet, Text, View, TouchableOpacity, Animated } from 'react-native'; import CAStyles fro ...

Transfer files using Ajax and FormData technique

I have extensively researched various topics on this issue and prefer not to rely on any external plugins. function addToDatabase(menuItem){ var formData = new FormData(); formData.append("Description", document.getElementById("DescriptionID").value); ...

What is the best approach for creating a JSON object using a PHP array?

I am in the process of extracting line items from a woocommerce store and require to transmit the information through an API using JSON format. While I have managed to create an array for the simpler section of this JSON example, I am struggling with this ...

What is the method to store and retrieve data attributes linked to elements such as select options within the React framework?

Despite my efforts, I'm currently unable to retrieve the data attribute from an option using React as it keeps returning null. <select onChange={(e) => this.onIndustryChangeOption(e)} value={this.props.selectedIndustry}> <opti ...

What is the best way to display the selected value of a radio button in React Native?

Being relatively new to React Native and mobile app development in general, I am facing an issue while trying to display the values assigned to different radio buttons within a radio button group. My code snippet is provided below: RadioButtons.js im ...

Having trouble with the href attribute not properly redirecting to a different page

I am trying to create a hyperlink for an option that will take users to another page. All the other options on the page lead to different sections within the same page. When I add CONTACT, it doesn't work. All the files are in the same ...

Reducing HTML content to 20 words efficiently through the use of JS and VueJS

Currently in the process of developing a news feed using VueJS and have encountered an issue with rendering the content. Unfortunately, the API I am working with does not allow for easy customization to fit my specific needs. This API provides all the cont ...

Shadows in Three.js are failing to render

After reviewing all the shadow-related posts here, none of them seemed to apply to my issue or I may have just missed it about 10 times. Check out this link for more information. I wanted to create a fiddle for this problem, but unfortunately, the versio ...

Transform JSON data that illustrates an array into an array of strings

There is an external string that represents a JSON array. Here's how it looks: ["abc", "xyz", "123"] The goal is to parse this into a String[] and then iterate over its elements. Currently, the code snippet outlines the intention of using the parse ...

How to monitor the status of a PHP script running in the background using AJAX?

Looking for a way to monitor the state of a PHP script running in the background? Want to create a simple progress bar? One idea is to send an AJAX request to file A.php, which will add a parameter to the session and then wait for a response. Meanwhile, s ...

Modifying a value in a two-dimensional array through a mutator function in Java

I'm currently working on a Battleship program consisting of three classes: a driver, a domain, and a helper class. In my domain class, I'm trying to update the value of an element in a 2D array of chars using a mutator method. However, I keep enc ...

Loading a GLTF model directly from a file input with ThreeJS

When using ThreeJS, I want to allow the user to load any GLTF model they choose to display. To achieve this, I have implemented a file input tag where the user can click and select a gltf-file to upload from their file browser: <input id="selectedM ...

What is the best approach to implementing a filter in Vue 2 that is also compatible with Vue 3?

Currently, I am utilizing Vue.js 2+ version and have implemented a date formatting filter to meet my needs. However, I recently found out that Vue 3 has removed the filter functionality in favor of using computed properties or methods. My dilemma now is ho ...

What is the process for importing the TokenExpiredError that is thrown by the verify function in jsonwebtoken?

Is there a way to determine if an Error object thrown by the jwt.verify function in the jsonwebtoken library is of type TokenExpiredError using Typescript's instanceof? For example: import jwt from "jsonwebtoken"; function someFunction() { try { ...

Is Material-UI suitable for a large-scale enterprise application?

We are in the process of transforming a massive and outdated MVC Java EE application into React. This particular application consists of a browser-based user interface with an extensive range of views that include intricate forms, listings, and links. It i ...

What is the correct way to utilize the submit() function within this specific form?

I have a small registration form that requires validation before submission. In order to achieve this, I've developed a JavaScript function as shown below: var name = document.getElementById('name').value; var company = document.getElem ...

Using Inline Styling to Showcase a Background Image in a REACTJS Component

import React from 'react'; import Slick from 'react-slick'; import style from './Slider.module.css'; import {Link} from 'react-router-dom'; const SliderTemplates = (props) => { let template = null; const ...

Increasing values in Mongoose using $inc can be done by following these steps

I've been struggling to increment a field value using $inc in my code. My schema looks like this: var postSchema = mongoose.Schema({ title : { type: String, required: true }, body : { type: String, default: '' }, coun ...