-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.

1
  • 2
    j.map(i => ({ User1_Score: i.Score_A, User2_Score: i.Score_B }))? Commented Feb 5, 2021 at 9:47

1 Answer 1

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)

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

2 Comments

"Event more neat with new syntax" — I dunno, just seems more verbose…
@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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.