Need a way to randomly pick a value from an array of objects without traversing the parent

Viewed 90

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.

3 Answers

You could build an array from the various tags elements, and use that to do random things.

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"
                            ]
                        }
                    ]
                }
            ]
        }
    }
}

const 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;
}, []);

const randomIndex = Math.floor(Math.random() * arrayOfTags.length);

const randomTag = arrayOfTags[randomIndex];

console.log(randomTag.tag, randomTag.response);

You will need to mine the tags, put them together into an array and randomize the index, finally get the value there. The solution below assumes that your tags are all arrays inside data.Total_packages[whateverpackage]

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"
                            ]
                        }
                    ]
                }
            ]
        }
    }
}

let tags = [];
for (let key in data.Total_packages) {
    if (data.Total_packages[key].tags) tags = tags.concat(data.Total_packages[key].tags);
}
console.log(tags[parseInt(tags.length * Math.random())]);

EDIT

In the comment section you have mentioned that you have duplicates of the form of

[
  {
    "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"
            ]
          }
        ]
      }
    ]
  }
]

This is how you can get rid of duplicates:

let input = [
  {
    "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"
            ]
          }
        ]
      }
    ]
  }
];

let output = input.filter((item, index) => {
    return input.filter((item2, index2) => {
        return ((item.tag === item2.tag) && (index2 < index));
    }).length === 0;
});

console.log(output);

We search for items who have no matches on earlier indexes.

i saved all tags in a separate array and kept the ref of expectedResponse in the block. then it's a matter or randomly selecting one tag index and matching with the block expectedResponse index. probably needs some adjustment to the random/length but i hope it puts you in the right direction.

var tags = []
var block = Object.values(data.Total_packages).flat()
block.forEach(item => tags = [...tags, ...item.tags])

var index = tags[parseInt(tags.length * Math.random())]
console.log(block[Math.floor(tags.indexOf(index) / 4)].expectedResponse)
Related