IITGIAN
IITGIAN

Reputation: 1

Associating keys to JSON arrays not having keys using javascript

I have several JSON arrays. They look like

[["Vishnu", 25],["Joginder", 22],["Amar", 27],["Rohan", 24],["Karan", 23]]

I want to prepare a Javascript code to convert these array of arrays to JSON arrays but with keys, which looks like:

[{"Player": "Vishnu", "Age": 25},{"Player": "Joginder", "Age": 22},{"Player": "Amar", "Age": 27},{"Player": "Rohan", "Age": 24},{"Player": "Karan", "Age": 23}]

Can anyone provide me some idea, or a code for it.

Upvotes: 0

Views: 60

Answers (3)

synthet1c
synthet1c

Reputation: 6282

You can use Array.map() to iterate over the players array and call a function over each element. The returned value from each iteration will create a new Array

var players = [["Vishnu", 25],["Joginder", 22],["Amar", 27],["Rohan", 24],["Karan", 23]]

// map over the players multidimensional array
var playersObjects = players.map(function(player) {
  // inside the callback player is the current element
  // return an object with the correct properties
  return {
    Player: player[0],
    Age: player[1]
  }
})

console.log(playersObjects)

Upvotes: 0

brk
brk

Reputation: 50326

The first array is an array of arrays(2D) array, while the new array that you intend to create need to be an array of json objects.

var orArray = [
  ["Vishnu", 25],
  ["Joginder", 22],
  ["Amar", 27],
  ["Rohan", 24],
  ["Karan", 23]
];

var newJsonArray = [];

// loop through the original array
orArray.forEach(function(item) {
  //check if item is an array
  if (Array.isArray(item)) {
    var _obj = {}; // Create an empty object;
    _obj.Player = item[0];// create first key;
    _obj.Age = item[1]; //Push second key
    newJsonArray.push(_obj) // Push to new array
  }
})
console.log(newJsonArray)

DEMO

Upvotes: 0

guest271314
guest271314

Reputation: 1

You can use Array.prototype.map() to return an array of objects, where first element of array is set to value of property "Player", second element of array is set as value for property "Age"

var arr = [["Vishnu", 25]
          ,["Joginder", 22]
          ,["Amar", 27]
          ,["Rohan", 24]
          ,["Karan", 23]
          ];

var res = arr.map(function(el, index) {
   return {"Player":el[0], "Age": el[1]}
});

console.log(res);

Upvotes: 2

Related Questions