Using for loops create new object with other objects with matching id's











up vote
0
down vote

favorite












I'm not sure if this is the best way to write this code..



object.array.forEach((item) => {
object.otherarray.array.forEach((asset) => {
if(item.fields.image.sys.id === asset.sys.id) {
item.fields.image['fields'] = asset.fields;
}
})
});


any help would be appreciated!










share|improve this question






















  • With some assumptions I can suggest the following remake: object.array.forEach((item) => { item.fileds.image.fields = object.otherarray.array.filter( (asset) => item.fields.image.sys.id === asset.sys.id )[0].fields; }); or object.array.forEach((item) => { const imageId = item.fields.image.sys.id; item.fileds.image.fields = object.otherarray.array .filter((asset) => imageId === asset.sys.id)[0].fields; });
    – FreeLightman
    19 hours ago










  • @FreeLightman could you post that in the answer field please
    – Smokey Dawson
    19 hours ago






  • 1




    you can checkout my answer.
    – FreeLightman
    19 hours ago










  • What should happen if there is more than one matching asset or if there are no matching assets?
    – Marc Rohloff
    7 hours ago















up vote
0
down vote

favorite












I'm not sure if this is the best way to write this code..



object.array.forEach((item) => {
object.otherarray.array.forEach((asset) => {
if(item.fields.image.sys.id === asset.sys.id) {
item.fields.image['fields'] = asset.fields;
}
})
});


any help would be appreciated!










share|improve this question






















  • With some assumptions I can suggest the following remake: object.array.forEach((item) => { item.fileds.image.fields = object.otherarray.array.filter( (asset) => item.fields.image.sys.id === asset.sys.id )[0].fields; }); or object.array.forEach((item) => { const imageId = item.fields.image.sys.id; item.fileds.image.fields = object.otherarray.array .filter((asset) => imageId === asset.sys.id)[0].fields; });
    – FreeLightman
    19 hours ago










  • @FreeLightman could you post that in the answer field please
    – Smokey Dawson
    19 hours ago






  • 1




    you can checkout my answer.
    – FreeLightman
    19 hours ago










  • What should happen if there is more than one matching asset or if there are no matching assets?
    – Marc Rohloff
    7 hours ago













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I'm not sure if this is the best way to write this code..



object.array.forEach((item) => {
object.otherarray.array.forEach((asset) => {
if(item.fields.image.sys.id === asset.sys.id) {
item.fields.image['fields'] = asset.fields;
}
})
});


any help would be appreciated!










share|improve this question













I'm not sure if this is the best way to write this code..



object.array.forEach((item) => {
object.otherarray.array.forEach((asset) => {
if(item.fields.image.sys.id === asset.sys.id) {
item.fields.image['fields'] = asset.fields;
}
})
});


any help would be appreciated!







javascript






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 20 hours ago









Smokey Dawson

1134




1134












  • With some assumptions I can suggest the following remake: object.array.forEach((item) => { item.fileds.image.fields = object.otherarray.array.filter( (asset) => item.fields.image.sys.id === asset.sys.id )[0].fields; }); or object.array.forEach((item) => { const imageId = item.fields.image.sys.id; item.fileds.image.fields = object.otherarray.array .filter((asset) => imageId === asset.sys.id)[0].fields; });
    – FreeLightman
    19 hours ago










  • @FreeLightman could you post that in the answer field please
    – Smokey Dawson
    19 hours ago






  • 1




    you can checkout my answer.
    – FreeLightman
    19 hours ago










  • What should happen if there is more than one matching asset or if there are no matching assets?
    – Marc Rohloff
    7 hours ago


















  • With some assumptions I can suggest the following remake: object.array.forEach((item) => { item.fileds.image.fields = object.otherarray.array.filter( (asset) => item.fields.image.sys.id === asset.sys.id )[0].fields; }); or object.array.forEach((item) => { const imageId = item.fields.image.sys.id; item.fileds.image.fields = object.otherarray.array .filter((asset) => imageId === asset.sys.id)[0].fields; });
    – FreeLightman
    19 hours ago










  • @FreeLightman could you post that in the answer field please
    – Smokey Dawson
    19 hours ago






  • 1




    you can checkout my answer.
    – FreeLightman
    19 hours ago










  • What should happen if there is more than one matching asset or if there are no matching assets?
    – Marc Rohloff
    7 hours ago
















With some assumptions I can suggest the following remake: object.array.forEach((item) => { item.fileds.image.fields = object.otherarray.array.filter( (asset) => item.fields.image.sys.id === asset.sys.id )[0].fields; }); or object.array.forEach((item) => { const imageId = item.fields.image.sys.id; item.fileds.image.fields = object.otherarray.array .filter((asset) => imageId === asset.sys.id)[0].fields; });
– FreeLightman
19 hours ago




With some assumptions I can suggest the following remake: object.array.forEach((item) => { item.fileds.image.fields = object.otherarray.array.filter( (asset) => item.fields.image.sys.id === asset.sys.id )[0].fields; }); or object.array.forEach((item) => { const imageId = item.fields.image.sys.id; item.fileds.image.fields = object.otherarray.array .filter((asset) => imageId === asset.sys.id)[0].fields; });
– FreeLightman
19 hours ago












@FreeLightman could you post that in the answer field please
– Smokey Dawson
19 hours ago




@FreeLightman could you post that in the answer field please
– Smokey Dawson
19 hours ago




1




1




you can checkout my answer.
– FreeLightman
19 hours ago




you can checkout my answer.
– FreeLightman
19 hours ago












What should happen if there is more than one matching asset or if there are no matching assets?
– Marc Rohloff
7 hours ago




What should happen if there is more than one matching asset or if there are no matching assets?
– Marc Rohloff
7 hours ago










2 Answers
2






active

oldest

votes

















up vote
2
down vote













In this loop object.otherarray.array you use id property to to ensure to have necessary match. So I assume this item.fields.image.sys.id === asset.sys.id always should have only one match. And it resulted in the following code:



object.array.forEach((item) => {
item.fileds.image.fields = object.otherarray.array.filter(
(asset) => item.fields.image.sys.id === asset.sys.id
)[0].fields;
});


Some explanation:



object.otherarray.array.filter(
(asset) => item.fields.image.sys.id === asset.sys.id
)[0];


is an equivalent of your item.fields.image.sys.id === asset.sys.id. In other words, firstly we find necessary asset. Then when we have it we can use fields property to assign it to item.fileds.image.fields.



I also have another variant of my remake:



object.array.forEach((item) => {
const imageId = item.fields.image.sys.id;
item.fileds.image.fields = object.otherarray.array
.filter((asset) => imageId === asset.sys.id)
[0].fields;
});


While it is more verbose version, it is more clear and structive so I would recommend to use this one.



I am open to your comments as I suppose I could not understand your correctly.






share|improve this answer





















  • Is there any reason you chose to use filter instead of find?
    – Marc Rohloff
    7 hours ago


















up vote
0
down vote













Note



Code review is for working code, not a generic "How I might write some functionality?" which I feel your example is. I must take the code at face value and that it is in accordance to the site rules.



General points




  • The array otherarray is poorly named and should be otherArray.

  • Additionally the names array and otherarray are extremely poor and give no clue as to what they hold. Never name variable to their type, name them for what they represent.

  • Why use the more complicated bracket notation for accessing fields there is no need. item.fields.image['fields'] can be item.fields.image.fields

  • Single parameters for Arrow functions do not need to be delimited with (...) thus array.forEach((item) => { can be array.forEach(item => {

  • Reduce complexity by assigning long property paths in the outer loop (see example for item.fields.image.sys.id)

  • This is inline code and not a good example of quality code. Always encapsulate functionality in a function.

  • As a function you can extract the two arrays via parameter destructuring (see examples).


  • It may or may not be a requirement that you copy the reference to fields to the first array, meaning that any changes to the original will appear in the copied reference.



    As your intent is unclear I will just point out that you can make a shallow copy using item.fields.image.fields = {...asset.fields} or if the left side exists you may want to just copy over existing fields and add new ones with Object.assign(item.fields.image.fields,asset.fields);




Complexity



Without the data I must make an assumption that there is only a one to one match for otherarray and array on items sys.id which makes the inner loop inefficient because you keep looping after you have found the only match. If this is not the case then you would be assigning the last match in which case you would use a for ; ; or while loop to iterate backward to find the last match.



Reducing inner iterations via Array.some or for...of



You could use array.some to find the first match which can greatly reduce the number of iterations needed. Or more efficiently you can use a for...of loop and break once a match is found. Both solutions below.



Example using Array.some



function assignFieldsToMatchId({array, otherArray}) { 
array.forEach(item => {
const id = item.fields.image.sys.id;
otherArray.array.some(asset => {
if (id === asset.sys.id) {
item.fields.image.fields = asset.fields;
return true; // breaks out of the inner loop.
}
return false;
})
});
}
assignFieldsToMatchId(object); /// You need to ensure otherarray is named otherArray


Example using inner for...of



function assignFieldsToMatchId({array, otherArray}) { 
array.forEach(item => {
const id = item.fields.image.sys.id;
for (const asset of otherArray.array) {
if (id === asset.sys.id) {
item.fields.image.fields = asset.fields;
break;
}
}
});
}
assignFieldsToMatchId(object); /// You need to ensure otherarray is named otherArray


Example using only for...of



Using for...of loops are always slightly more efficient than the Array iterators like forEach



function assignFieldsToMatchId({array, otherArray}) { 
for (const item of array) {
const id = item.fields.image.sys.id;
for (const asset of otherArray.array) {
if (id === asset.sys.id) {
item.fields.image.fields = asset.fields;
break;
}
}
}
}
assignFieldsToMatchId(object); /// You need to ensure otherarray is named otherArray





share|improve this answer























    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208106%2fusing-for-loops-create-new-object-with-other-objects-with-matching-ids%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    2
    down vote













    In this loop object.otherarray.array you use id property to to ensure to have necessary match. So I assume this item.fields.image.sys.id === asset.sys.id always should have only one match. And it resulted in the following code:



    object.array.forEach((item) => {
    item.fileds.image.fields = object.otherarray.array.filter(
    (asset) => item.fields.image.sys.id === asset.sys.id
    )[0].fields;
    });


    Some explanation:



    object.otherarray.array.filter(
    (asset) => item.fields.image.sys.id === asset.sys.id
    )[0];


    is an equivalent of your item.fields.image.sys.id === asset.sys.id. In other words, firstly we find necessary asset. Then when we have it we can use fields property to assign it to item.fileds.image.fields.



    I also have another variant of my remake:



    object.array.forEach((item) => {
    const imageId = item.fields.image.sys.id;
    item.fileds.image.fields = object.otherarray.array
    .filter((asset) => imageId === asset.sys.id)
    [0].fields;
    });


    While it is more verbose version, it is more clear and structive so I would recommend to use this one.



    I am open to your comments as I suppose I could not understand your correctly.






    share|improve this answer





















    • Is there any reason you chose to use filter instead of find?
      – Marc Rohloff
      7 hours ago















    up vote
    2
    down vote













    In this loop object.otherarray.array you use id property to to ensure to have necessary match. So I assume this item.fields.image.sys.id === asset.sys.id always should have only one match. And it resulted in the following code:



    object.array.forEach((item) => {
    item.fileds.image.fields = object.otherarray.array.filter(
    (asset) => item.fields.image.sys.id === asset.sys.id
    )[0].fields;
    });


    Some explanation:



    object.otherarray.array.filter(
    (asset) => item.fields.image.sys.id === asset.sys.id
    )[0];


    is an equivalent of your item.fields.image.sys.id === asset.sys.id. In other words, firstly we find necessary asset. Then when we have it we can use fields property to assign it to item.fileds.image.fields.



    I also have another variant of my remake:



    object.array.forEach((item) => {
    const imageId = item.fields.image.sys.id;
    item.fileds.image.fields = object.otherarray.array
    .filter((asset) => imageId === asset.sys.id)
    [0].fields;
    });


    While it is more verbose version, it is more clear and structive so I would recommend to use this one.



    I am open to your comments as I suppose I could not understand your correctly.






    share|improve this answer





















    • Is there any reason you chose to use filter instead of find?
      – Marc Rohloff
      7 hours ago













    up vote
    2
    down vote










    up vote
    2
    down vote









    In this loop object.otherarray.array you use id property to to ensure to have necessary match. So I assume this item.fields.image.sys.id === asset.sys.id always should have only one match. And it resulted in the following code:



    object.array.forEach((item) => {
    item.fileds.image.fields = object.otherarray.array.filter(
    (asset) => item.fields.image.sys.id === asset.sys.id
    )[0].fields;
    });


    Some explanation:



    object.otherarray.array.filter(
    (asset) => item.fields.image.sys.id === asset.sys.id
    )[0];


    is an equivalent of your item.fields.image.sys.id === asset.sys.id. In other words, firstly we find necessary asset. Then when we have it we can use fields property to assign it to item.fileds.image.fields.



    I also have another variant of my remake:



    object.array.forEach((item) => {
    const imageId = item.fields.image.sys.id;
    item.fileds.image.fields = object.otherarray.array
    .filter((asset) => imageId === asset.sys.id)
    [0].fields;
    });


    While it is more verbose version, it is more clear and structive so I would recommend to use this one.



    I am open to your comments as I suppose I could not understand your correctly.






    share|improve this answer












    In this loop object.otherarray.array you use id property to to ensure to have necessary match. So I assume this item.fields.image.sys.id === asset.sys.id always should have only one match. And it resulted in the following code:



    object.array.forEach((item) => {
    item.fileds.image.fields = object.otherarray.array.filter(
    (asset) => item.fields.image.sys.id === asset.sys.id
    )[0].fields;
    });


    Some explanation:



    object.otherarray.array.filter(
    (asset) => item.fields.image.sys.id === asset.sys.id
    )[0];


    is an equivalent of your item.fields.image.sys.id === asset.sys.id. In other words, firstly we find necessary asset. Then when we have it we can use fields property to assign it to item.fileds.image.fields.



    I also have another variant of my remake:



    object.array.forEach((item) => {
    const imageId = item.fields.image.sys.id;
    item.fileds.image.fields = object.otherarray.array
    .filter((asset) => imageId === asset.sys.id)
    [0].fields;
    });


    While it is more verbose version, it is more clear and structive so I would recommend to use this one.



    I am open to your comments as I suppose I could not understand your correctly.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 19 hours ago









    FreeLightman

    23817




    23817












    • Is there any reason you chose to use filter instead of find?
      – Marc Rohloff
      7 hours ago


















    • Is there any reason you chose to use filter instead of find?
      – Marc Rohloff
      7 hours ago
















    Is there any reason you chose to use filter instead of find?
    – Marc Rohloff
    7 hours ago




    Is there any reason you chose to use filter instead of find?
    – Marc Rohloff
    7 hours ago












    up vote
    0
    down vote













    Note



    Code review is for working code, not a generic "How I might write some functionality?" which I feel your example is. I must take the code at face value and that it is in accordance to the site rules.



    General points




    • The array otherarray is poorly named and should be otherArray.

    • Additionally the names array and otherarray are extremely poor and give no clue as to what they hold. Never name variable to their type, name them for what they represent.

    • Why use the more complicated bracket notation for accessing fields there is no need. item.fields.image['fields'] can be item.fields.image.fields

    • Single parameters for Arrow functions do not need to be delimited with (...) thus array.forEach((item) => { can be array.forEach(item => {

    • Reduce complexity by assigning long property paths in the outer loop (see example for item.fields.image.sys.id)

    • This is inline code and not a good example of quality code. Always encapsulate functionality in a function.

    • As a function you can extract the two arrays via parameter destructuring (see examples).


    • It may or may not be a requirement that you copy the reference to fields to the first array, meaning that any changes to the original will appear in the copied reference.



      As your intent is unclear I will just point out that you can make a shallow copy using item.fields.image.fields = {...asset.fields} or if the left side exists you may want to just copy over existing fields and add new ones with Object.assign(item.fields.image.fields,asset.fields);




    Complexity



    Without the data I must make an assumption that there is only a one to one match for otherarray and array on items sys.id which makes the inner loop inefficient because you keep looping after you have found the only match. If this is not the case then you would be assigning the last match in which case you would use a for ; ; or while loop to iterate backward to find the last match.



    Reducing inner iterations via Array.some or for...of



    You could use array.some to find the first match which can greatly reduce the number of iterations needed. Or more efficiently you can use a for...of loop and break once a match is found. Both solutions below.



    Example using Array.some



    function assignFieldsToMatchId({array, otherArray}) { 
    array.forEach(item => {
    const id = item.fields.image.sys.id;
    otherArray.array.some(asset => {
    if (id === asset.sys.id) {
    item.fields.image.fields = asset.fields;
    return true; // breaks out of the inner loop.
    }
    return false;
    })
    });
    }
    assignFieldsToMatchId(object); /// You need to ensure otherarray is named otherArray


    Example using inner for...of



    function assignFieldsToMatchId({array, otherArray}) { 
    array.forEach(item => {
    const id = item.fields.image.sys.id;
    for (const asset of otherArray.array) {
    if (id === asset.sys.id) {
    item.fields.image.fields = asset.fields;
    break;
    }
    }
    });
    }
    assignFieldsToMatchId(object); /// You need to ensure otherarray is named otherArray


    Example using only for...of



    Using for...of loops are always slightly more efficient than the Array iterators like forEach



    function assignFieldsToMatchId({array, otherArray}) { 
    for (const item of array) {
    const id = item.fields.image.sys.id;
    for (const asset of otherArray.array) {
    if (id === asset.sys.id) {
    item.fields.image.fields = asset.fields;
    break;
    }
    }
    }
    }
    assignFieldsToMatchId(object); /// You need to ensure otherarray is named otherArray





    share|improve this answer



























      up vote
      0
      down vote













      Note



      Code review is for working code, not a generic "How I might write some functionality?" which I feel your example is. I must take the code at face value and that it is in accordance to the site rules.



      General points




      • The array otherarray is poorly named and should be otherArray.

      • Additionally the names array and otherarray are extremely poor and give no clue as to what they hold. Never name variable to their type, name them for what they represent.

      • Why use the more complicated bracket notation for accessing fields there is no need. item.fields.image['fields'] can be item.fields.image.fields

      • Single parameters for Arrow functions do not need to be delimited with (...) thus array.forEach((item) => { can be array.forEach(item => {

      • Reduce complexity by assigning long property paths in the outer loop (see example for item.fields.image.sys.id)

      • This is inline code and not a good example of quality code. Always encapsulate functionality in a function.

      • As a function you can extract the two arrays via parameter destructuring (see examples).


      • It may or may not be a requirement that you copy the reference to fields to the first array, meaning that any changes to the original will appear in the copied reference.



        As your intent is unclear I will just point out that you can make a shallow copy using item.fields.image.fields = {...asset.fields} or if the left side exists you may want to just copy over existing fields and add new ones with Object.assign(item.fields.image.fields,asset.fields);




      Complexity



      Without the data I must make an assumption that there is only a one to one match for otherarray and array on items sys.id which makes the inner loop inefficient because you keep looping after you have found the only match. If this is not the case then you would be assigning the last match in which case you would use a for ; ; or while loop to iterate backward to find the last match.



      Reducing inner iterations via Array.some or for...of



      You could use array.some to find the first match which can greatly reduce the number of iterations needed. Or more efficiently you can use a for...of loop and break once a match is found. Both solutions below.



      Example using Array.some



      function assignFieldsToMatchId({array, otherArray}) { 
      array.forEach(item => {
      const id = item.fields.image.sys.id;
      otherArray.array.some(asset => {
      if (id === asset.sys.id) {
      item.fields.image.fields = asset.fields;
      return true; // breaks out of the inner loop.
      }
      return false;
      })
      });
      }
      assignFieldsToMatchId(object); /// You need to ensure otherarray is named otherArray


      Example using inner for...of



      function assignFieldsToMatchId({array, otherArray}) { 
      array.forEach(item => {
      const id = item.fields.image.sys.id;
      for (const asset of otherArray.array) {
      if (id === asset.sys.id) {
      item.fields.image.fields = asset.fields;
      break;
      }
      }
      });
      }
      assignFieldsToMatchId(object); /// You need to ensure otherarray is named otherArray


      Example using only for...of



      Using for...of loops are always slightly more efficient than the Array iterators like forEach



      function assignFieldsToMatchId({array, otherArray}) { 
      for (const item of array) {
      const id = item.fields.image.sys.id;
      for (const asset of otherArray.array) {
      if (id === asset.sys.id) {
      item.fields.image.fields = asset.fields;
      break;
      }
      }
      }
      }
      assignFieldsToMatchId(object); /// You need to ensure otherarray is named otherArray





      share|improve this answer

























        up vote
        0
        down vote










        up vote
        0
        down vote









        Note



        Code review is for working code, not a generic "How I might write some functionality?" which I feel your example is. I must take the code at face value and that it is in accordance to the site rules.



        General points




        • The array otherarray is poorly named and should be otherArray.

        • Additionally the names array and otherarray are extremely poor and give no clue as to what they hold. Never name variable to their type, name them for what they represent.

        • Why use the more complicated bracket notation for accessing fields there is no need. item.fields.image['fields'] can be item.fields.image.fields

        • Single parameters for Arrow functions do not need to be delimited with (...) thus array.forEach((item) => { can be array.forEach(item => {

        • Reduce complexity by assigning long property paths in the outer loop (see example for item.fields.image.sys.id)

        • This is inline code and not a good example of quality code. Always encapsulate functionality in a function.

        • As a function you can extract the two arrays via parameter destructuring (see examples).


        • It may or may not be a requirement that you copy the reference to fields to the first array, meaning that any changes to the original will appear in the copied reference.



          As your intent is unclear I will just point out that you can make a shallow copy using item.fields.image.fields = {...asset.fields} or if the left side exists you may want to just copy over existing fields and add new ones with Object.assign(item.fields.image.fields,asset.fields);




        Complexity



        Without the data I must make an assumption that there is only a one to one match for otherarray and array on items sys.id which makes the inner loop inefficient because you keep looping after you have found the only match. If this is not the case then you would be assigning the last match in which case you would use a for ; ; or while loop to iterate backward to find the last match.



        Reducing inner iterations via Array.some or for...of



        You could use array.some to find the first match which can greatly reduce the number of iterations needed. Or more efficiently you can use a for...of loop and break once a match is found. Both solutions below.



        Example using Array.some



        function assignFieldsToMatchId({array, otherArray}) { 
        array.forEach(item => {
        const id = item.fields.image.sys.id;
        otherArray.array.some(asset => {
        if (id === asset.sys.id) {
        item.fields.image.fields = asset.fields;
        return true; // breaks out of the inner loop.
        }
        return false;
        })
        });
        }
        assignFieldsToMatchId(object); /// You need to ensure otherarray is named otherArray


        Example using inner for...of



        function assignFieldsToMatchId({array, otherArray}) { 
        array.forEach(item => {
        const id = item.fields.image.sys.id;
        for (const asset of otherArray.array) {
        if (id === asset.sys.id) {
        item.fields.image.fields = asset.fields;
        break;
        }
        }
        });
        }
        assignFieldsToMatchId(object); /// You need to ensure otherarray is named otherArray


        Example using only for...of



        Using for...of loops are always slightly more efficient than the Array iterators like forEach



        function assignFieldsToMatchId({array, otherArray}) { 
        for (const item of array) {
        const id = item.fields.image.sys.id;
        for (const asset of otherArray.array) {
        if (id === asset.sys.id) {
        item.fields.image.fields = asset.fields;
        break;
        }
        }
        }
        }
        assignFieldsToMatchId(object); /// You need to ensure otherarray is named otherArray





        share|improve this answer














        Note



        Code review is for working code, not a generic "How I might write some functionality?" which I feel your example is. I must take the code at face value and that it is in accordance to the site rules.



        General points




        • The array otherarray is poorly named and should be otherArray.

        • Additionally the names array and otherarray are extremely poor and give no clue as to what they hold. Never name variable to their type, name them for what they represent.

        • Why use the more complicated bracket notation for accessing fields there is no need. item.fields.image['fields'] can be item.fields.image.fields

        • Single parameters for Arrow functions do not need to be delimited with (...) thus array.forEach((item) => { can be array.forEach(item => {

        • Reduce complexity by assigning long property paths in the outer loop (see example for item.fields.image.sys.id)

        • This is inline code and not a good example of quality code. Always encapsulate functionality in a function.

        • As a function you can extract the two arrays via parameter destructuring (see examples).


        • It may or may not be a requirement that you copy the reference to fields to the first array, meaning that any changes to the original will appear in the copied reference.



          As your intent is unclear I will just point out that you can make a shallow copy using item.fields.image.fields = {...asset.fields} or if the left side exists you may want to just copy over existing fields and add new ones with Object.assign(item.fields.image.fields,asset.fields);




        Complexity



        Without the data I must make an assumption that there is only a one to one match for otherarray and array on items sys.id which makes the inner loop inefficient because you keep looping after you have found the only match. If this is not the case then you would be assigning the last match in which case you would use a for ; ; or while loop to iterate backward to find the last match.



        Reducing inner iterations via Array.some or for...of



        You could use array.some to find the first match which can greatly reduce the number of iterations needed. Or more efficiently you can use a for...of loop and break once a match is found. Both solutions below.



        Example using Array.some



        function assignFieldsToMatchId({array, otherArray}) { 
        array.forEach(item => {
        const id = item.fields.image.sys.id;
        otherArray.array.some(asset => {
        if (id === asset.sys.id) {
        item.fields.image.fields = asset.fields;
        return true; // breaks out of the inner loop.
        }
        return false;
        })
        });
        }
        assignFieldsToMatchId(object); /// You need to ensure otherarray is named otherArray


        Example using inner for...of



        function assignFieldsToMatchId({array, otherArray}) { 
        array.forEach(item => {
        const id = item.fields.image.sys.id;
        for (const asset of otherArray.array) {
        if (id === asset.sys.id) {
        item.fields.image.fields = asset.fields;
        break;
        }
        }
        });
        }
        assignFieldsToMatchId(object); /// You need to ensure otherarray is named otherArray


        Example using only for...of



        Using for...of loops are always slightly more efficient than the Array iterators like forEach



        function assignFieldsToMatchId({array, otherArray}) { 
        for (const item of array) {
        const id = item.fields.image.sys.id;
        for (const asset of otherArray.array) {
        if (id === asset.sys.id) {
        item.fields.image.fields = asset.fields;
        break;
        }
        }
        }
        }
        assignFieldsToMatchId(object); /// You need to ensure otherarray is named otherArray






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 15 hours ago

























        answered 15 hours ago









        Blindman67

        6,5091521




        6,5091521






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208106%2fusing-for-loops-create-new-object-with-other-objects-with-matching-ids%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Costa Masnaga

            Fotorealismo

            Sidney Franklin