I have this code where it will log the value into the console
const table = { index: 0,
data: {items:[
{students: {name: Gloria, age: 24, gender: female} , id: 025},
{students: {name: Alex, age: 27, gender: male} , id: 024}],
total: 2}
}
const result = table.data.items.map(Object.values);
console.log(result);
and the console will appear as
[[{name: Gloria, age: 24, gender: female} , 025],
[{name: Alex, age: 27, gender: male} , id: 024]]
The only problem is I want only the values to appear such as
[[{Gloria, 24, female}, 025],
[{Alex, 27, male}, 024]
can somebody tell me what is wrong in here?
CodePudding user response:
for this below
[[{Gloria, 24, female}, 025],
[{Alex, 27, male}, 024]
this object is not valid since Objects should have key-value pairs,
{Gloria, 24, female}
This below is valid
[[{name: Gloria, age: 24, gender: female} , 025],
[{name: Alex, age: 27, gender: male} , id: 024]]
or you can make it like this :
[[[Gloria, 24, female], 025],
[[Alex, 27, male], 024]
Do lemme know if this works, ill let you know how to do that
EDIT: ANSWER :
const table = { index: 0,
data: {items:[
{students: {name: "Gloria", age: 24, gender: "female"} , id: 25},
{students: {name: "Alex", age: 27, gender: "male"} , id: 24}],
total: 2}
}
/*
[[[Gloria, 24, female], 025],
[[Alex, 27, male], 024] */
const result = table.data.items.map((data) => {
const newArr = [];
newArr.push(data.id)
const {age,gender,name} = data.students
const secondArr = [name,age,gender];
newArr.push(secondArr)
return newArr
});
console.log(result);
CodePudding user response:
Can use Array.map()
and callback function to achive that.
But will be a little differnet to this format
[[{Gloria, 24, female}, 025],
[{Alex, 27, male}, 024]
example:
const table = {
index: 0,
data: {
items:[
{students: {name: "Gloria", age: 24, gender: "female"} , id: 25},
{students: {name: "Alex", age: 27, gender: "male"} , id: 24}],
total: 2}
}
const result = table.data.items.map((x) => {
let studentArray = [x.students.name, x.students.gender];
return [studentArray, x.id];
});
console.log(result);
console.log(result[0]);
console.log(result[1]);