Reputation: 7
I'm trying to iterate over a JSON object in Cypress but haven't found a solution anywhere so far. The closest thing I've found is how to iterate over all the items in an array:
cy.wrap({fieldsArr}).each((value) => {
cy.get('[data-for="' + field + '"]').type(value)
})
The incorrect solutions I've come up with are:
// JSON object
// Error: cy.each() can only operate on an array like subject.
cy.wrap({fieldsBI: valueBI}).each((field,value) => {
cy.get('[data-for="' + field + '"]').type(value)
})
// Spreading the object as 2 arrays
// end up with m*n cy.gets
cy.wrap(fieldsArr).each((field) => {
cy.wrap(valueArr)((value) => {
cy.get('[data-for="' + field + '"]').type(value)
})
})
I have looked at cy.wrap/spread/then but nothing came up.
For reference: I am looking to get:
cy.get('[data-for="' + field1 + '"]').type(value1)
cy.get('[data-for="' + field2 + '"]').type(value2)
cy.get('[data-for="' + field3 + '"]').type(value3)
cy.get('[data-for="' + field4 + '"]').type(value4)
Upvotes: -1
Views: 1804
Reputation: 8352
If you need to get a value of each key, you can try the following:
const foo = {
a: 1,
b: 2,
};
cy
.get(Object.values(foo)).each(value => {
cy.log(value);
});
or you can get the keys and access easily both the keys and values:
const foo = {
a: 1,
b: 2,
};
cy
.get(Object.keys(foo)).each(key => {
cy.log(`${key} ${data[key]}`);
});
Or you can use Object.entries()
:
const foo = {
a: 1,
b: 2,
};
cy
.get(Object.entries(foo)).each(([key, value]) => {
cy.log(`${key} ${value}`);
});
There might be better solution based on how your object is stored. For example, you can use cy.fixture()
if your data are located in a file.
Or perhaps you don't need to store parts of selectors at all and just select the right elements with cy.get()
.
Or perhaps you can change your data structure to something like:
const foo = [
{
selector: 'a',
value: 1,
},
{
selector: 'b',
value: 2,
}
];
cy
.wrap(foo).each(({selector, value}) => {
cy.log(`${selector} ${value}`);
});
This last example would probably make sense to me because each object in the array is separate from other objects and their selectors and data. It seems to me that you're putting unrelated things into one object, that's why I included this last example.
Upvotes: -1
Reputation: 32062
Turn an object into an array of tuples [key, value]
with Object.entries()
cy.wrap(Object.entries({fieldsBI: valueBI})).each(([field, value]) => {
cy.get(`[data-for="${field}"]`) // easier with template string
.type(value)
})
Upvotes: 1