Search code examples
javascriptecmascript-6ecmascript-5

How to replace specific key elements in array with elements of another array


I have an array object of variable length and i want to replace specific key elements of whole array with another array object which is also of variable length. I have tried different array methods but i am stuck at this one. I have 6 months of programming experience.

My code is:

a = [
 { id: 1, name: "Alex", qty: 6, prodCode: 1321 }, 
 { id: 2, name: "carry", qty: 2, prodCode: 1641 }, 
 { id: 1, name: "manuel", qty: 7, prodCode: 1754 },
.....]

b= [{qty:5},{qty:9},{qty:2},...]
a.length===b.length

Result should be like:

[
  { id: 1, name: "Alex", qty: 5, prodCode: 1321 }, 
  { id: 2, name: "carry", qty: 9, prodCode: 1641 }, 
  { id: 1, name: "manuel", qty: 2, prodCode: 1754 },
.....]

Solution

  • For simplicity, this is what needs to be done

    for( let index = 0; index < objectArray.length; index++ ){
    
       objectArray[index].qty = qtys[index].qty;
    
    }
    

    You can use the Browser's js console to understand where each value resides in a JSON Object and how to get a value from it.

    For example, run this in the console after initializing the objectArray

    objectArray[0].qty // This will give qty of the first object in the array
    

    You can use this to navigate inside a complicated object