-3

I currently have a JSON object result which looks like the following:

[
    {
        "Score_A": -112.166458,
        "Score_B": 33.462795,
        "Rating": 3,
        "Team_Score": 5.01
    },
    {
        "Score_A": -112.11248,
        "Score_B": 33.510269,
        "Rating": 3,
        "Team_Score": 5.01
    },
    {
        "Score_A": -112.06501,
        "Score_B": 33.523769,
        "Rating": 2,
        "Team_Score": 5.02
    }
]

I want to store this in a variable new_result by removing the fields Rating and Team_Score. I also want to change the key for Score_A and Score_B to User1_Score and User2_Score respectively.

How can I do this?

Expected Result new_result:

[
    {
        "User1_Score": -112.166458,
        "User2_Score": 33.462795
    },
    {
        "User1_Score": -112.11248,
        "User2_Score": 33.510269
    },
    {
        "User1_Score": -112.06501,
        "User2_Score": 33.523769
    }
]

Note: The length of result is never constant.

Akhil Kintali
  • 496
  • 2
  • 11
  • 27

1 Answers1

1

The array.map function should do it:

data = [
    {
        "Score_A": -112.166458,
        "Score_B": 33.462795,
        "Rating": 3,
        "Team_Score": 5.01
    },
    {
        "Score_A": -112.11248,
        "Score_B": 33.510269,
        "Rating": 3,
        "Team_Score": 5.01
    },
    {
        "Score_A": -112.06501,
        "Score_B": 33.523769,
        "Rating": 2,
        "Team_Score": 5.02
    }
]

result = data.map(item => ({
    user1_score: item.Score_A,
    user2_score: item.Score_B
}))

// Event more neat with new syntax:

result = data.map(({ Score_A, Score_B }) => ({
    user1_score: Score_A,
    user2_score: Score_B
}))

console.log(result)
Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
  • *"Event more neat with new syntax"* — I dunno, just seems *more* verbose… – deceze Feb 05 '21 at 09:53
  • @deceze opinions... I could argue that i like it because it shows _what we need_ in the data for the result to happen. But whatever, I just show both options and op can choose! – Ulysse BN Feb 05 '21 at 10:43