Skip to content
Advertisement

How can i add fields inside empty array?

Good morning guys

I have to create a new JSON object array using the user array but when I do this getting the below error. could someone help me here? or help me to understand the mistake?

var users = [{ "name":"John", "age":30, "car":"fiat" },{ "name":"Raj", "age":28, "car":"hundai" }];

var allUser =[]

for (var i = 0; i < users.length; i++) {
  test(i, users[i])
}
console.log(allUser)

function test(i, user) {
  console.log(i)
  <!-- allUser.push({"username":user.name}); -->

  allUser[i].username = user.name;
  //allUser[i].userage = user.age;
  //allUser[i].usercar = user.car;
}

enter image description here

Expected Result:

all user should be like this

[{ "username":"John", "userage":30 },{ "username":"Raj", "userage":28 }]

Advertisement

Answer

Your test function can be fixed in the following manner:

var users = [
  { "name": "John", "age": 30, "car": "fiat"   },
  { "name": "Raj",  "age": 28, "car": "hundai" },
];

var allUser = [];

for (var i = 0; i < users.length; i++) {
  test(i, users[i]);
}
console.log(allUser);

function test(i, user) {
  allUser[i] = {}; // create and assign a new object to `allUser[i]`
  allUser[i].username = user.name;
  allUser[i].userage = user.age;
  allUser[i].usercar = user.car;
}

However the above looks over complicated, and a map call would simplify things a lot.

var users = [
  { "name": "John", "age": 30, "car": "fiat"   },
  { "name": "Raj",  "age": 28, "car": "hundai" },
];

var allUser = users.map((user) => ({
  username: user.name,
  userage: user.age,
  usercar: user.car,
}));

console.log(allUser);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement