简体   繁体   中英

Nested Object.keys() are printing properties multiple times instead of only once

I have two objects that I need to loop through so I can use their properties later on. However if I print the variables each of them is printed twice. I understand that because I have the Object.keys() inside other Object.keys() . Is there any way to loop through these two objects and only get each variable one time?

My code:

Object.keys(newData.name).map(async key => {
    Object.keys(newData._temp.images).map(async keyImage => {
        console.log(newData.name[key].name,'printed 2x instead of once');
        console.log(newData._temp.images[keyImage].rawFile.preview, 'printed 2x instead of once');
    });
});

Thank you in advance.

your logic here of nesting the loops is wrong.

these 2 object does not seem to be connected to one another, meaning you do not need the data from the first loop in order to perform the other loops. just split it into 2 seperate loops, would save you both time and repititions:

let nameKeys = Object.keys(newData.name).map(key => newData.name[key].name);
let imagesKeys = Object.keys(newData._temp.images).map(keyImage => 
                 newData._temp.images[keyImage].rawFile.preview);

now you can access nameKeys and imageKeys whenever you want, and they will contain the values you previously logged. My naming might be a bit off tho, feel free to change that:D

Also, as others mentioned- no need for the async keyword... you do not perform any async operation inside (yet, at least. if thats what you're planning then go ahead and keep it).

These iterators do not need to be nested. The second iterator is not looping through an item of the first iterator.

Object.keys(newData.name).forEach(key => {
    console.log(newData.name[key].name);
});
Object.keys(newData._temp.images).forEach(keyImage => {
    console.log(keyImage[keyImage].rawFile.preview);
});

If you are only iterested in outputting data, then .map() is not the right function to use because this is used when you care about the return value. Use .forEach() if you just want to loop through things.

Also, the async keyword is not needed here.. unless you plan to do some async/await stuff in the loops later!

You could iterate over the indices once and then access the values in both arrays:

 const names = Object.keys(newData.name);
 const images = Object.keys(newData._temp.images);

for(let i = 0; i < Math.min(names.length, images.length); i++) {
  const name = names[i];
  const image = images[i];
  //...
}

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