Creating separate arrays into another array from data of an object

Simply use Array.prototype.map which is designed for creating a new array from an existing one, where the resulting array will have exactly the same length as the original array:

const data = [{ Name: "Jack", accuracy: "average", accent: 79, weight: 1 },{ Name: "Sara", accuracy: "good", accent: 24, weight: 2 },{ Name: "Nick", accuracy: "not bad", accent: 89, weight: 1 },{ Name: "Doe", accuracy: "good", accent: 88, weight: 4 },{ Name: "Lee", accuracy: "excellent", accent: 63, weight: 9 },{ Name: "Sasha", accuracy: "good", accent: 42, weight: 5 }]

const list = [data.map(x=>x.Name), data.map(x=>x.accuracy)];

console.log(list);


Change declaration of list to include the sub arrays you want to push to.

Then your code works fine

var list = [[],[]];


var data = [];

data[0] = { Name: "Jack", accuracy: "average", accent: 79, weight: 1 };
data[1] = { Name: "Sara", accuracy: "good", accent: 24, weight: 2 };
data[2] = { Name: "Nick", accuracy: "not bad", accent: 89, weight: 1 };
data[3] = { Name: "Doe", accuracy: "good", accent: 88, weight: 4 };
data[4] = { Name: "Lee", accuracy: "excellent", accent: 63, weight: 9 };
data[5] = { Name: "Sasha", accuracy: "good", accent: 42, weight: 5 };

for ( var i=0; i < data.length; i++ ) {
 list[0].push( data[i].Name );
 list[1].push( data[i].accuracy);
}
console.log(list);


Try this with reduce:

 
var data = [];

data[0] = { Name: "Jack", accuracy: "average", accent: 79, weight: 1 };
data[1] = { Name: "Sara", accuracy: "good", accent: 24, weight: 2 };
data[2] = { Name: "Nick", accuracy: "not bad", accent: 89, weight: 1 };
data[3] = { Name: "Doe", accuracy: "good", accent: 88, weight: 4 };
data[4] = { Name: "Lee", accuracy: "excellent", accent: 63, weight: 9 };
data[5] = { Name: "Sasha", accuracy: "good", accent: 42, weight: 5 };

const list = data.reduce((acc,ele)=>{
 acc[0].push(ele.Name);
 acc[1].push(ele.accuracy);
 return acc
}, [[], []])

console.log(list);

Tags:

Javascript