简体   繁体   中英

How to get the last array iteration in javascript in a map function?

I want to create an Array of objects in a messages constant which are 3 keys /values : author , hour and message

Problem : some object have a blank author value, and I want to get the previous iteration author key/value in the .map function itself to replace the blank value (current iteration)

Is it possible to get the previous iteration element in the .map function even if the iteration is not yet finished ?

Thanks a lot for your help

From this

0:
author: "Kara"
hour: "19:32"
message: "Salut Mia merci pour ton ajout cela va me servir de test !"
1:
author: ""
hour: ""
message: "Ceci est un test : message 2 !!" 

To this :


0:
author: "Kara"
hour: "19:32"
message: "Salut Mia merci pour ton ajout cela va me servir de test !"
1:
author: "Kara"
hour: "19:32"
message: "Ceci est un test : message 2 !!" 

I want to copy the previous iteration object values.

Is it possible to get the previous iteration element in the .map function even if the iteration is not yet finished ?

Yes. The second argument is the current index and the third argument is the array itself, so you can just access array[index - 1] inside the .map callback. That won't work for the first element though (as there is no previous element).

You can use the index from the handler:

array.map((o, index, arr) => {
   let previous = arr[index - 1]; // For index === 0, the previous object will be undefined.
});

Go and read about it -> Array.prototype.map

array.map((ele, index, arr) => {
   let keys = Object.keys(ele);
   keys.each((key) => {
    if (ele[key] === '') {
     ele[key] = arr[index - 1][key];
    }
   });
   return ele;
});

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