skip to Main Content

I have an object like this:

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

Here’s the request that I need to implement: https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate

I want to create an array of objects and pass the key of my object to the value of "text". for example "name" goes to {{text1}} and "Alexa" to "replaceText1" dynamically.

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

2

Answers


  1. You can map the Object.entries of obj.param to create a request object for each key/value pair, then place that as the value in 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)
    Login or Signup to reply.
  2. Try this out. This uses Object.entries to get the key, value pair and they are used as a resulting objects. You can parse the params object using JSON.parse.

    params = {
    "name": "Alexa",
    "lastName": "Simpson",
    "city": "London"
    }
    
    requests = []
    
    for (const [k, v] of Object.entries(params)) {
      requests.push({
    "replaceAllText": {
      "containsText": {
        "text": k,
        "matchCase": "true"
      }
    },
    "replaceText": v
      })
    }
    
    console.log(`{requests: ${JSON.stringify(requests)}`)

    Use JSON.stringify to convert to the resulting string.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search