Build an intricate nested array structure using the properties of an object

My data object is structured like this:

"parameters": {
    "firstName": "Alexa",
    "lastName": "Simpson",
    "city": "London"
  }

The task at hand involves implementing the following request: https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate

I aim to construct an array of objects where the key of my data object corresponds to the value of "text". For example, "firstName" should map to {{text1}} and "Alexa" should map to "replaceText1" dynamically.

{
  "requests": [
    {
      "replaceAllText": {
        "containsText": {
          "text": "{{text1}}",
          "matchCase": "true"
        },
        "replaceText": "replaceText1"
      }
    },
    {
      "replaceAllText": {
        "containsText": {
          "text": "{{value2}}",
          "matchCase": "true"
        },
        "replaceText": "replaceText2"
      }
    }
    
  ]
}

Answer №1

To transform the key/value pairs of obj.param into request objects, you can utilize the Object.entries method along with the map function. Each pair is used to create an object with a key of requests:

const obj = {
  "params": {
    "name": "Alexa",
    "lastName": "Simpson",
    "city": "London"
  }
}

const req = {
  "requests": Object.entries(obj.params).map(([text, value]) =>
    ({
      "replaceAllText": {
        "containsText": {
          "text": text,
          "matchCase": "true"
        },
        "replaceText": value
      }
    }))
}

console.log(req)

Answer №2

Give this a shot. This code snippet utilizes the Object.entries method to extract the key-value pairs from an object and create new objects based on them. You can then parse the `params` object using JSON.parse.

params = {
"name": "Alice",
"lastName": "Smith",
"city": "Paris"
}

requests = []

for (const [key, value] of Object.entries(params)) {
  requests.push({
    "replaceAllText": {
      "containsText": {
        "text": key,
        "matchCase": "true"
      }
    },
    "replaceText": value
  })
}

console.log(`{requests: ${JSON.stringify(requests)}`)

Utilize JSON.stringify to convert the resulting output into a string.

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

Combining Kafka as the source with mqtt and using jdbc as the sink

I am using Kafka and have configured a MQTT broker as the data source. The JSON configuration for this setup is as follows: { "name": "mqtt-source", "config": { "connector.class": "io.confluent.connect.mqtt. ...

Modify the internal value of a nested array

I have a challenge where I need to update a specific value in a recursive array. The array contains the path to the variable that needs to be changed: $scopePath is the designated path for the update. For instance, if $scopePath==Array("owners","product ...

What is preventing me from using JavaScript to remove this class?

Struggling to implement a skeleton loading screen with CSS classes and JavaScript. The idea is to apply the 'skeleton' class to elements, style them accordingly, then remove the class using a timeout set in JavaScript. However, I'm encounter ...

Finding the automatically generated ID of a new document in a subcollection in Firebase Firestore Web V9, using Javascript/React

When a user clicks, I generate a new document in a subcollection associated with that user's profile. Below is the function responsible for this: // Function to create a new checkout session document in the subcollection under the user's profile ...

Unable to utilize library post npm import

Recently, I attempted to integrate the flexibility library into my Laravel project. Following the installation with npm i flexibility --save, I required it in my app.js file: require('flexibility/flexibility.js'); ... flexibility(document.docume ...

Transform the Standard class into a generic one in typescript

I've created a class that can take JSON objects and transform them into the desired class. Here's the code: import {plainToClass} from "class-transformer"; import UserDto from "../../auth/dto/user.dto"; class JsonConverter { ...

Style the labels on the axis of Frappe Charts with colors (potentially utilizing the appropriate CSS selector)

Is it possible to style the x and y axis labels in a Frappe chart with different colors? https://i.stack.imgur.com/A3vUq.png While trying to identify the CSS selectors using Chrome DevTools, I found that a single text element (representing an x axis labe ...

"Looking to display an image object retrieved from AWS S3 using a signed URL in Vue.js? Here's how you

<div v-for="(data, key) in imgURL" :key="key"> <img :src= "getLink(data)" /> </div> imgURL here is an array that contains file names. methods: { async getLink(url){ let response = await PostsService.downloadURL({ i ...

Filtering Key Presses in Quasar: A Comprehensive Guide

Seeking Assistance I am looking to integrate an "Arabic keyboard input filtering" using the onkeyup and onkeypress events similar to the example provided in this link. <input type="text" name="searchBox" value="" placeholder="ب ...

What steps can I take to fix the Error with webpack's style hot loader JavaScript?

Just starting out with native script and encountered an issue when running this code: <template> <view class="container"> <text class="text-color-primary">My Vue Native Apps</text> </view> </template> &l ...

Utilizing Vue.js to initiate a server request with vue-resource

Seeking guidance on performing a server call using vue-resource. I'm unsure about how to set the header and send data via Vue.$http.post Vue.$http.post('http://url/', { email: 'foo', password: 'bar' }, { headers: { ...

Dropdown Placement Based on Button Click

Looking to create an interactive dropdown menu with the Alloy UI Dropdown Component that appears when a user clicks on one of four buttons. The goal is for this dropdown to be positioned to the left of the clicked button. var toolsDropdown = new Y.Dropdow ...

a guide on transforming a string array into JSON

I initialized an array like this String[] finalcodes = new String[50] ; and populated it with some values. However, when I print finalcodes, the output is: ["aaa","bbb","ccc"] My goal is to convert this string array into a JSON Object. Can someone pl ...

Learn how to extract information from the Australian Bureau of Statistics by utilizing pandasmdx

Has anyone successfully retrieved ABS data using the pandasdmx library? Below is an example code that retrieves data from the European Central Bank (ECB) and works as expected. from pandasdmx import Request ecb = Request('ECB') flow_response ...

Exploring the art of json parsing using Alamofire in the latest Swift 5

As a beginner in iOS programming, I am currently trying to retrieve data from a WordPress JSON and display it in a table view. However, I am facing the issue: value of type 'Any' has no subscripts whenever I attempt to create an object from t ...

Reacting to URL Changes but Failing to Load the Requested Page

Welcome to my App Component import React, { useEffect } from 'react'; import './App.css'; import Navbar from './components/layout/Navbar'; import Landing from './components/layout/Landing'; import { BrowserRouter as ...

The content inside an HTML element and covertly deciphered quotations

SETTING THE SCENE: Hidden within the page lies a perfectly structured JSON object, wrapped in a div. Within this object are HTML values encoded with double-quotes, creating a unique challenge: "additionalInfo": "If you need more help, please visit &l ...

Calculate the combined sum and alter the values of three input fields

There are three text boxes (testbox, testbox2, testbox3) that receive values from an input field, radio button selection, and checkbox. The correct values are displayed in testbox, testbox2, testbox3. Additionally, the sum of testbox, testbox2, testbox3 n ...

Is the initial carousel element failing to set height to 100% upon loading?

If you take a look here, upon loading the page you will notice a DIV at the top. It is labeled "content" with "content_container" wrapped around it and finally, "page" around that. Clicking the bottom left or right arrows reveals other DIVs with similar ta ...

Search results do not remove previous data after typing

After creating a live-search-inline-x-editable page, I encountered an issue with the live search functionality. While everything works smoothly with x-editable, the problem arises when conducting a search query. Each time a character is entered into the s ...