Skip to content
Advertisement

How to get a particular attribute from an array of array objects?

I have an Array of Arrays, and each Array consists of objects. Here is a simplified version of what I’m referring to (it is a console.log of my original array) –

Array - [Array(2), Array(3), Array(2)]

Each Array has objects in the following format (taking the first array from above) –

Array(2) - 
0: {name: "test", score:40, date: "2018-09-18T00:00:00.000Z"}
1: {name: "test2", score:50 date: "2018-09-18T00:00:00.000Z"}

The other arrays are similar with the same attributes and different values.

I am trying to fetch the name attribute from each of these objects. I tried the below code – but I end up getting an undefined value:

const test1= array1.map(x=> x.values) // this gives me the array of arrays
const test2 = test1.map(function(y){return y.name})// this is my attempt to get the 'name' attribute from all of the arrays that include the objects.

What am I missing out on here? Is there a better way to get the attribute using arrow functions?

Advertisement

Answer

/* TEST DATA */
array1 = [
  { name: 'test1', score: 40, date: '2018-09-18T00:00:00.000Z' },
];
array2 = [
  { name: 'test4', score: 50, date: '2018-09-18T00:00:00.000Z' },
  { name: 'test5', score: 40, date: '2018-09-18T00:00:00.000Z' }, 
];
array3 = [
  { name: 'test6', score: 50, date: '2018-09-18T00:00:00.000Z' },
  { name: 'test7', score: 50, date: '2018-09-18T00:00:00.000Z' },
  { name: 'test8', score: 40, date: '2018-09-18T00:00:00.000Z' },
  { name: 'test9', score: 50, date: '2018-09-18T00:00:00.000Z' },
];

testResults = [array1, array2, array3];

// Solution 

function getListOfName(){
  let names = [];
  testResults.map(testResult => {
    testResult.map(({name}) => {if(name) names.push(name)})
  })
  return names;
}
console.log("Full list of names", getListOfName());

// If you want to restrict to K names from each array
function getFirstKNamesfromArray(limit){
  let names = [];
  testResults.map(testResult => {
    testResult.map(({name}, index) => {
      if(name && (index < limit)) names.push(name)
    })
  })
  return names
}
console.log("First 2 names from each array", getFirstKNamesfromArray(2));
Advertisement