i want do make object from 2D array and the output only like this
{ firstName: 'd', lastName: 'e', gender: 'f' }
this is my code
function x(y) {
var z = {}
for (a = 0; a < y.length; a++) {
z.firstName = y[a][0]
z.lastName = y[a][1]
z.gender = y[a][2]
}
return z
}
var y = [
["a", "b", "c"],
["d", "e", "f"]
]
console.log(x(y))
what's wrong with this code? why it skip the first line of array when looping?
You need to return an array of objects, not a single object that you keep overwriting in the loop.
function x(y) {
var result = [];
for (let a = 0; a < y.length; a++) {
let z = {};
z.firstName = y[a][0];
z.lastName = y[a][1];
z.gender = y[a][2];
result.push(z);
}
return result;
}
var y = [
["a", "b", "c"],
["d", "e", "f"]
]
console.log(x(y))
You can also simplify it using map().
function x(y) {
return y.map(i => ({
firstName: i[0],
lastName: i[1],
gender: i[2]
}));
}
var y = [
["a", "b", "c"],
["d", "e", "f"]
]
console.log(x(y))
You are overwriting the property inside the object,
check the code snippet below
function x(y) {
const z = []
for (let a = 0; a < y.length; a++) {
z.push({
firstName:y[a][0],
lastName:y[a][1],
gender:y[a][2],
})
}
return z
}
var y = [
["a", "b", "c"],
["d", "e", "f"]
]
console.log(x(y))
You are overwriting the values of z.firstName, z.lastName and z.gender during your second loop, an object may not contain duplicate values
You should consider defining z as an array and using the array.push() method.