user2241956
user2241956

Reputation: 17

Cypress: read, modify and write a json file with a variable as a name of a field

I'm wrapping my head around a function that reads, adds fields and writes JSON back to the file in Cypress:

writeCounterFile(counterName, c) {
    const filename =  Cypress.env("counterFilePath")
    cy.readFile(filename).then((obj) => {
        obj.counterName = c
        cy.writeFile(filename, obj)
    })
    return c
}

I'm passing the field name string in counterName argument in the function above trying to get the JSON file content look like:

{
   "counter1": NN,
   "counter2": XX,
   "counter3": YY
}

But the function results in {"counterName": YY} because, aparently, obj.counterName doesn't recognise counterName as the variable.

Plese, help.

Upvotes: 0

Views: 2176

Answers (1)

user14783414
user14783414

Reputation:

There's two ways to add properties to an object, the first with dot notation (.) - as you saw what follows the dot is (literally) the property name.

The second is bracket notation where the property name is given in a variable, this is the one you want

obj[counterName] = c

Ref Property accessors

Syntax

object.property
object['property']

Upvotes: 1

Related Questions