1

I currently have an array that has 2 levels. I am attempting to build two new arrays from the initial array but seem to be stuck with the method to use. I have attempted a forEach(), while loop, as well as push to no avail.

My current array structure:

[
  {
    "attributes": {
      "Summary": 10,
      "class": "Blue"
    }
  },
  {
    "attributes": {
      "Summary": 63,
      "class":"Red"
    }
  }
]

I am looking to build two arrays, namely one for summary values, and one for class values.

Are my approaches of a forEach or while loop on the correct path?

WhaleShark
  • 89
  • 2
  • 11
  • 3
    `"I currently have an array that has 2 levels."` no, you have one array containing objects – caramba Jun 23 '21 at 11:10
  • Yes. You need to loop through the array and also might have to use something like Object.keys() at some point. Try that, if that doesn't help do share what is the output you expect. – Tushar Shahi Jun 23 '21 at 11:11
  • 1
    Please share the code which you tried and expected output. – Hassan Imam Jun 23 '21 at 11:12

2 Answers2

5

If you have an array and want to transform that into another array, the simplest way is to use map (which basically creates a new array containing the results of running each element through a function):

const arr = [
  {
    "attributes": {
      "Summary": 10,
      "class": "Blue"
    }
  },
  {
    "attributes": {
      "Summary": 63,
      "class":"Red"
    }
  }
];
const summaries = arr.map(e => e.attributes.Summary);
const classes = arr.map(e => e.attributes.class);

gustafc
  • 28,465
  • 7
  • 73
  • 99
2

If you want to accomplish this using forEach, here's one way to do it:

const aryInitial = [
  {
    "attributes": {
      "Summary": 10,
      "class": "Blue"
    }
  },
  {
    "attributes": {
      "Summary": 63,
      "class":"Red"
    }
  }
];
let arySummary = [];
let aryClass = [];

aryInitial.forEach((obj)=>
{
  arySummary.push(obj.attributes.Summary);
  aryClass.push(obj.attributes.class);
});
console.log("Summary Array:",arySummary);
console.log("Class Array:",aryClass);
Lonnie Best
  • 9,936
  • 10
  • 57
  • 97