Jason
Jason

Reputation: 7682

From arrow function, push object to array

The async/await function search returns an object similar to:

[
  {
    "title":"page title",
    "url":"/page/url/index.html",
    "content":"blah blah blah"
  },
  ...
]

I need to push each object from val into the array, but when I push using:

results = [];
search(input).then(val=> results.push(val));

I get a nested array similar to (I want to the object entries to be top level in the array):

[
  [
    {title:"...", url:"...", content:"..."},
    {title:"...", url:"...", content:"..."},
  ]
]

So I tried a for in the arrow to push each entry in the object into the array, but that didn't seem to work.

results = [];
search(input).then(val=> for(i in val) {results.push(val[i])});

Upvotes: 0

Views: 2730

Answers (4)

ffflabs
ffflabs

Reputation: 17481

If you have an array and call a function that will return Promise<array> you don't need to perform any iteration on the result. Concatenate the arrays:

async function getNewData() {
  return Promise.resolve([{
    d: 1
  }, {
    e: 3
  }]);
}

let results = [{
  a: 3
}, {
  b: 4
}];

getNewData().then(newdata => {
  results = results.concat(newdata); 
  // same as results = [...results, ...newdata];

  console.log(results);
});

On the other hand, you could also push using the spread operator

async function getNewData() {
  return Promise.resolve([{
    d: 1
  }, {
    e: 3
  }]);
}

const results = [{
  a: 3
}, {
  b: 4
}];

getNewData().then(newdata => {
  results.push(...newdata); 
  // same as results.push(newdata[0], newdata[1], etc)

  console.log(results);
});

This approach might be confusing as people tend to ignore the variadic nature of Array.prototype.push, but it avoids redeclaring results, so you may declare the target array as const.

Upvotes: 2

PeterKA
PeterKA

Reputation: 24638

Instead of .push(), use .concat()

results = [];
search(input).then(val=> { results = results.concat(val) });

Upvotes: 3

Ajeet Eppakayala
Ajeet Eppakayala

Reputation: 1435

Use spread syntax ...

No For loop needed either.

search(input).then(val=> results = [...results,...val]);

or as @Patrick_Hund suggested

search(input).then(val=> results.push(...val));

here problem is that you are pushing array in to an array.

You need to push the elements of array.

Spreading syntax should fix the issue.

Hope you have clear understanding now.

Upvotes: 2

Yatrix
Yatrix

Reputation: 13785

If you want to use a for loop, you'll have to do

for(var i=0; i < val.length; i++) {
    results.push(val[i])
}

There are more succinct ways to do this (see Patrick Hund's comment), but that's how you do it with a for loop.

Upvotes: 1

Related Questions