简体   繁体   中英

How can I push data from an array/object into another array/object?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM