0

The app I'm working on building uses a XMLHttpRequest and I've parsed the the responsetext into a variable called data3 that returns this:

[]
0: {round_fk: "1", player_name: "John Doe", player_score: "-45"}
1: {round_fk: "1", player_name: "Mark Doe", player_score: "-7"}
2: {round_fk: "2", player_name: "Dave Doe", player_score: "-7"}
3: {round_fk: "2", player_name: "Chris Doe", player_score: "-7"}

I'm trying to sort through this array of objects based on the round_fk and put all of the rounds with the same round_fk in another array where each object has a key that corresponds to the round_fk. It would look something like this:

let sortRounds = [
    [
      1: round_fk: "1", player_name: "John Doe", player_score: "-45",
         round_fk: "1", player_name: "Mark Doe", player_score: "-7"
    ],
    [
      2: round_fk: "2", player_name: "Dave Doe", player_score: "-7",
         round_fk: "2", player_name: "Chris Doe", player_score: "-7"
    ]
];

So far this is what I have:

let sortRound = [];
          console.log(sortRound);
          for(i = 0; i < data3.length; i++){
            let roundFk = data3[i].round_fk;
            if(!(roundFk in sortRound)){
              sortRound[roundFk] = [];
            }
            Object.keys(sortRound).forEach(function(key){
              if(key == roundFk){
                key.push(data3[i]);
              }
            });
          }

I create an array with keys that correspond to the round_fk, but when I try to push data into these new keys, I get the following error message "Uncaught TypeError: key.push is not a function".

I've changed my objects from regular objects to arrays, shouldn't the push function be working now? Where am I going wrong here? I've been stuck on this for a while now, any help is greatly appreciated!

Thanks! Chris

1 Answer 1

2

There are better ways to do this, but let's start by fixing the problem.

The error says Uncaught TypeError: key.push is not a function. This is referring to this line:

key.push(data3[i]);

This should be

sortedRounds[key].push(data3[i]);

Why?

You're trying to .push to a key. In an array (such as sortRounds), the keys look like [0,1,2]

So your code is equivalent to 0.push(data3[i]). You can't push to 0! It's not an array.

Better solutions

let sortRound = [];
for(i = 0; i < data3.length; i++){
  let roundFk = data3[i].round_fk;
  if(!(roundFk in sortRound)){
    sortRound[roundFk] = [];
  }

  // We already know the correct key here, 
  // so no need to loop through the array again
  sortRound[roundFk].push(data3[i]);
}
Sign up to request clarification or add additional context in comments.

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.