简体   繁体   中英

retrieve the result of Array.map in javascript

I have a similar code to this structure. It seems as if I don't need the async functions here but like I said it's similar to my own code which is kind of long.

Here is my code:

const array = [
  { methods: 'user.js'},
  { methods: 'test.js'},
  { methods: 'hello.js' },
];
async function bigTest() {
  async function details() {
    const arr = [];
    const test = [];
    const files = array.map(async (i) => {
      arr.push({
        name: i,
        item: [
          {
            name: 'test',
          },
        ],
      });
      return test.push(arr);
    });
    return Promise.all(files);
  }
  const result = await details();
  console.log(JSON.stringify(result));
}
bigTest();

The console.log(arr) returns for me each time the process of pushing into the array:

[ { name: { methods: 'user.js', item: [] }, item: [ [Object] ] } ]

[ { name: { methods: 'user.js', item: [] }, item: [ [Object] ] },
  { name: { methods: 'test.js', item: [] }, item: [ [Object] ] } ]

[ { name: { methods: 'user.js', item: [] }, item: [ [Object] ] },
  { name: { methods: 'test.js', item: [] }, item: [ [Object] ] },
  { name: { methods: 'hello.js', item: [] }, item: [ [Object] ] } ] 

I want to return the last array with all the pushed element but what I get as a result is [1,2,3]

and when I do a console.log on the array test, I get duplicate objects

I want to return the last array with all the pushed element but what I get as a result is [1,2,3]

From MDN :

The push() method adds one or more elements to the end of an array and returns the new length of the array.

So you need to return the element itself and not the result of test.push(arr) . Replace return test.push(arr) by:

test.push(arr);
return test[test.length-1];

Then console.log only the last item in result :

console.log(JSON.stringify(result[result.length-1]));

 const array = [ { methods: 'user.js', item: [] }, { methods: 'test.js', item: [] }, { methods: 'hello.js', item: [] }, ]; async function bigTest() { async function details() { const arr = []; const test = []; const files = array.map(async (i) => { arr.push({ name: i, item: [{ name: 'test' }] }); test.push(arr); return test[test.length-1]; }); return Promise.all(files); } const result = await details(); console.log(JSON.stringify(result[result.length-1])); } bigTest();

I assume you are using arr and test for something else, otherwise, you could simplify your code a bit by getting rid of the intermediate arrays and logging the whole result array:

 const array = [ { methods: 'user.js', item: [] }, { methods: 'test.js', item: [] }, { methods: 'hello.js', item: [] }, ]; async function bigTest() { async function details() { return Promise.all(array.map(async (i) => ({ name: i, item: [{ name: 'test' }] }) )); } const result = await details(); console.log(JSON.stringify(result)); } bigTest();

return test.push(arr); does not give you the arr , it gives you the new length of test . Your files will be promises for integers, and your result will be an array of integers.

Additionally you create an array arr and also an array test to which you are repeatly pushing the arr . It doesn't seem like you want any nesting, so don't push multiple times.

You could instead return test or return arr , but you really simply shouldn't be push ing those values yourself. map already creates the new array for you, you just need to return the respective value from the callback:

async function bigTest() {
  const filePromises = array.map(async (i) => {
    // I assume you await something here, otherwise the `async` is really unnecessary
    return {
//  ^^^^^^
      name: i,
      item: [
        {
          name: 'test',
        },
      ],
    };
  });
  const files = await Promise.all(filePromises);
  console.log(JSON.stringify(files));
}

This line:

return test.push(arr);

is returning the new length of the test array, which is 1 then 2 then 3, so the files array ends up containing [1,2,3]

You probably want to replace:

return Promise.all(files);

with:

return Promise.all(files).then(() => arr);

which will execute the promises then return the contents of the arr array.

Alternatively, I'm not exactly sure what you're trying to do, but you may be able to simplify to:

async function bigTest() {
  async function details() {
    const files = array.map(async (i) => {
      return {
        name: i,
        item: [
          {
            name: 'test',
          },
        ],
      };
    });
    return Promise.all(files);
  }
  const result = await details();
  console.log(JSON.stringify(result));
}
bigTest();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM