Search a array of objects

Discussion in 'JavaScript' started by Lammie71, Jul 10, 2022.

  1. #1
    I have the following code:

    teams = [];
    teams[0] = new Object();
    teams[0].name = "Man Utd";
    teams[0] = [];
    teams[0][0] = new Object();
    teams[0][0].wins = 2;
    teams[0][0].defeats = [];
    teams[0][0].defeats[0] = [3,9,2,1];
    teams[0][0].pts = 4;

    teams[1] = new Object();
    teams[1].name = "Man City";
    teams[1] = [];
    teams[1][0] = new Object();
    teams[1][0].wins = 2;
    teams[1][0].defeats = [];
    teams[1][0].defeats[0] = [8,7,3];
    teams[1][0].pts = 12;

    How can I search for the array defeats for each team but substitute the word defeat with a numerical value?
     
    Last edited: Jul 10, 2022
    Lammie71, Jul 10, 2022 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,839
    Likes Received:
    4,542
    Best Answers:
    123
    Trophy Points:
    665
    #2
    Have you tried a map?

    let teams = [];
    teams[0] = {
      name: "Man Utd",
      wins: 2,
      defeats: [[3, 9, 2]],
      pts: 4
    };
    
    teams[1] = {
      name: "Man City",
      wins: 2,
      defeats: [[9, 7, 3]],
      pts: 12
    };
    
    const reworked = teams.map((row) =>  {...row, defeats: row.defeats[0]};
    Code (JavaScript):
     
    sarahk, Jul 10, 2022 IP
  3. Lammie71

    Lammie71 Greenhorn

    Messages:
    5
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    13
    #3
    Thanks for the reply, but using this code I am not sure what to do or how to see the new information. If I use document.write on reworked nothing appears.


     
    Lammie71, Jul 11, 2022 IP
  4. sarahk

    sarahk iTamer Staff

    Messages:
    28,839
    Likes Received:
    4,542
    Best Answers:
    123
    Trophy Points:
    665
    #4
    ofcourse not, it's still an array. You need to update your output code to use the new version of the array.
     
    sarahk, Jul 11, 2022 IP