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?

1

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Eldar, this worked perfectly. Just as an aside, is there a way to keep the id value with the flattened structure?
@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.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.