How can I extract multiple objects from within an Array

Asked

Viewed 63 times

2

I got a problem, I got a problem Array that returns me another Array with this group of objects inside:

let array = [
  {description: "Auto", amount: 15000, date: "17/02/2021"},
  {description: "Auto 2", amount: 12000, date: "17/02/2021"}
]

But this is done with a forEach in this way:

let array = []

newArray.forEach((transaction, index)=> {
    array.push(AutoTransations.Convert(transaction, index))   
})

return array

I was wondering if there’s a way to just pass the objects, not as a Array, so I would treat as an object not needing to make another forEach to get out of this New Array.

  • Place a sample of the newArray and explains what the AutoTransations.Convert() ago.

1 answer

3


What you have is similar to this, quite summarized:

function get_objects() {
  const array = [];
  
  for (let i = 0; i < 5; i++) {
    array.push({
      id: i
    });
  }
  
  return array;
}

console.log(get_objects());

However, you will have a sequence of objects in the return of your function, which today is represented by the object array. You can’t escape the loop of repetition to treat them all. There are some alternatives that might, in a way, mask you.

For example, you can convert your function to a generator and so do not need to store everything in memory at the same time:

function* get_objects() {
  for (let i = 0; i < 5; i++) {
    yield {id: i};
  }
}

for (let obj of get_objects()) {
  console.log(obj);
}

Or even apply a mapping if the operation is data extraction/conversion:

function get_objects() {
  const array = [];
  
  for (let i = 0; i < 5; i++) {
    array.push({
      id: i
    });
  }
  
  return array;
}

const objects = get_objects();

console.log(objects.map(obj => obj.id));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.