Syd Amir Syd Amir - 6 months ago 18
Node.js Question

the best way to change array in object to other obejct attr

I have an Array whith Object like this:



[
{
"position": "1",
"name": "FC Barcelona",
"data": [
"91",
"38",
"29",
"4",
"5",
"112",
"29"
]
},
{
"position": "2",
"name": "Real Madrid",
"data": [
"90",
"38",
"28",
"6",
"4",
"110",
"34"
]
},
{
"position": "3",
"name": "Atlético Madrid",
"data": [
"88",
"38",
"28",
"4",
"6",
"63",
"18"
]
}
]





and I want's to convert that to this in nodeJS backend in facet I want's to use vanilla javascript to convert :



[
{
"position": "1",
"name": "FC Barcelona",
"PTS": "91",
"Pld" "38",
"W": "29",
"D": "4",
"L": "5",
"GF": "112",
"GA": "29"
},
{
"position": "2",
"name": "Real Madrid",
"PTS": "90",
"Pld" "38",
"W": "28",
"D": "6",
"L": "4",
"GF": "110",
"GA": "34"
},
{
"position": "3",
"name": "Atlético Madrid",
"PTS": "88",
"Pld" "38",
"W": "28",
"D": "4",
"L": "6",
"GF": "63",
"GA": "18"
}
]





I want's to get the data array of any object in my master array and converted the any child of data array to child of the it's own object with the specific key i add to up code

Answer

You can do this with forEach

var ar = [{"position":"1","name":"FC Barcelona","data":["91","38","29","4","5","112","29"]},{"position":"2","name":"Real Madrid","data":["90","38","28","6","4","110","34"]},{"position":"3","name":"Atlético Madrid","data":["88","38","28","4","6","63","18"]}],
  result = [];

ar.forEach(function(e) {
  result.push({
    position: e.position,
    name: e.name,
    PT: e.data[0],
    Pld: e.data[1],
    W: e.data[2],
    D: e.data[3],
    L: e.data[4],
    GF: e.data[5],
    GA: e.data[6]
  })
})

console.log(result)

Comments