0

I'm struggling with understanding how to access a particular value that is in a nested array. Here's the data structure:

var data = [{id: "Game 1", count:[{date: datevalues, metric: values}] ,  rank: [{date: datevalues, metric: values}] },
{id: "Game 2", count: [{date: datevalues, metric: values}] ,  rank: [{date: datevalues, metric: values}] },
{id: "Game 3", count: [{date: datevalues, metric: values}] ,  rank: [{date: datevalues, metric: values}] },
{id: "Game 4", count: [{date: datevalues, metric: values}] ,  rank: [{date: datevalues, metric: values}] }]

Inside the array under both the count and rank keys are dictionaries with date and metric values, so going further, it looks like this:

[{date: "2017-01-01", metric: 100},
{date: "2018-01-01", metric: 90]...}]

My question is how do i directly access the date and metric fields?

Eldar
  • 9,781
  • 2
  • 10
  • 35
TBoneATL
  • 33
  • 1
  • 5
  • 1
    Does this answer your question? [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) ALSO: https://stackoverflow.com/questions/64050793/accesing-object-value-in-array-of-objects-by-conditioning-another-object-propert Also, when asking question add real sample data and wanted result so we know what are you trying to achieve , not guess – ikiK Mar 04 '21 at 20:42

2 Answers2

1

You can use Array.map, spread and Array.flat combined like below :

const datevalues = "2017-01-01";
const values = 1; 
var data = [{id: "Game 1", count:[{date: datevalues, metric: values}] ,  rank: [{date: datevalues, metric: values}] },
{id: "Game 2", count: [{date: datevalues, metric: values}] ,  rank: [{date: datevalues, metric: values}] },
{id: "Game 3", count: [{date: datevalues, metric: values}] ,  rank: [{date: datevalues, metric: values}] },
{id: "Game 4", count: [{date: datevalues, metric: values}] ,  rank: [{date: datevalues, metric: values}] }]

const mapped = data.map(r=> [...r.count,...r.rank]).flat()

const mappedWithIds = data.map(r=> [...r.count.map(q=> ({id:r.id,...q})),
                                    ...r.rank.map(q=> ({id:r.id,...q}))])
                                    .flat()

console.log(mapped)
console.log(mappedWithIds)
Eldar
  • 9,781
  • 2
  • 10
  • 35
  • Thanks @Eldar, this worked perfectly. Just as an aside, is there a way to keep the id value with the flattened structure? – TBoneATL Mar 05 '21 at 01:31
  • @Travis1585 yes there is a way which is to use the `Array.map` to pass the `id` value to the inner array. See the updated answer. – Eldar Mar 05 '21 at 06:15
0

You will need to have the id of the game. And then by getting the list of counts & ranks do a map for getting all the values from it.

const dates = data.filter(x => x.id)[0].count.map(x => x.date)
const metrics = data.filter(x => x.id)[0].count.map(x => x.metric)
Avedis Maroukian
  • 1,378
  • 3
  • 15
  • 26