I am still fairly new to JavaScript and need help with a task I am trying to accomplish.
I have an array of objects like this:
const data =
{
"Total_packages": {
"package1": {
"tags": [
"kj21",
"j1",
"sj2",
"z1"
],
"expectedResponse": [
{
"firstName": "Name",
"lastName": "lastName",
"purchase": [
{
"title": "title",
"category": [
"a",
"b",
"c"
]
}
]
}
]
},
"package2": {
"tags": [
"s2",
"dsd3",
"mhg",
"sz7"
],
"expectedResponse": [
{
"firstName": "Name1",
"lastName": "lastName1",
"purchase": [
{
"title": "title1",
"category": [
"a1",
"b1",
"c1"
]
}
]
}
]
},
"package3": {
"tags": [
"s21",
"dsd31",
"mhg1",
"sz71"
],
"expectedResponse": [
{
"firstName": "Name2",
"lastName": "lastName2",
"purchase": [
{
"title": "title2",
"category": [
"a2",
"b2",
"c2"
]
}
]
}
]
},
"package4": {
"tags": [
"s22",
"dsd32",
"mhg2",
"sz72"
],
"expectedResponse": [
{
"firstName": "Name3",
"lastName": "lastName3",
"purchase": [
{
"title": "title3",
"category": [
"a3",
"b3",
"c3"
]
}
]
}
]
},
"package5": {
"tags": [
"s22",
"dsd32",
"mhg2",
"sz72"
],
"expectedResponse": [
{
"firstName": "Name4",
"lastName": "lastName4",
"purchase": [
{
"title": "title4",
"category": [
"a4",
"b4",
"c4"
]
}
]
}
]
}
}
}
var arrRand = genNum(data, 3);
console.log(arrRand);
function genNum(data, loop='') {
var list = [];
var arrayOfTags = Object.entries(data.Total_packages).reduce((acc, [k, v]) => {
if (v.tags) acc = acc.concat(v.tags.map(t => ({tag: t, response: v.expectedResponse})));
return acc;
}, []);
for (var i = 0; i < loop; i++){
var randomIndex = Math.floor(Math.random() * arrayOfTags.length);
var randomTag = arrayOfTags[randomIndex];
list.push(randomTag);
}
return list;
}
I then access the values I need by doing something like arrRand[0].tag and arrRand[0].response.
Often times I get duplicate responses from the method such as following and it becomes problematic:
[
{
"tag": "s22",
"response": [
{
"firstName": "Name4",
"lastName": "lastName4",
"purchase": [
{
"title": "title4",
"category": [
"a4",
"b4",
"c4"
]
}
]
}
]
},
{
"tag": "dsd31",
"response": [
{
"firstName": "Name2",
"lastName": "lastName2",
"purchase": [
{
"title": "title2",
"category": [
"a2",
"b2",
"c2"
]
}
]
}
]
},
{
"tag": "dsd31",
"response": [
{
"firstName": "Name2",
"lastName": "lastName2",
"purchase": [
{
"title": "title2",
"category": [
"a2",
"b2",
"c2"
]
}
]
}
]
}
]
My goal is to send API requests with a random "tags" value from above and then match the response I get from the call to the expectedResponse part of the data.
My initial thought was to do something like:
data.Total_packages.tags[Math.floor(Math.random() * data.Total_packages.tags.length)];
However, I can't call on "tags" without traversing through its parent i.e "package1" or "package2", so then it won't be random anymore.
I know there is probably a very simple way to do it that I am not getting. Any advice would be appreciated.