Copy property value from matching objects between two arrays

I am using Angular 2 / Typescript.

I have an array "Items":

items: [
  {
    "id": 1,
    "qty" undefined
  },
  {
    "id": 2,
    "qty" undefined
  } 
  {
    "id": 3,
    "qty" undefined
  }...etc
]

      

Then I have an array "ItemsWithQuantities":

 itemsWithQuantities: [
      {
        "id": 1,
        "qty" 55
      },
      {
        "id": 2,
        "qty" 3
      } ...etc
    ]

      

I want to put qty values ​​from an array itemsWithQuantities

into the qty property of a match object (through id

) in the array items

. Obviously I could create a loop and a nested loop to find a match and set the property value, but I'm more interested in a refactored / eloquent solution. I'm wondering if there is something inline in typescript / "new" JS flavors or even lodash that might get me what I want.

+3


source to share


3 answers


You can use lodash merge !



    var items = [
      {
        "id": 1,
        "qty": undefined
      },
      {
        "id": 2,
        "qty": undefined
      },
      {
        "id": 3,
        "qty": undefined
      }
    ];
    
    var itemsWithQuantities = [
          {
            "id": 1,
            "qty": 55
          },
          {
            "id": 2,
            "qty": 3
          },
          {
          	"id": 3,
            "qty": 24
          }
    ];
        
    var answer = _.merge(itemsWithQuantities, items);
    console.log(answer);
      

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.5.1/lodash.min.js"></script>
      

Run code


jsfiddle

+1


source


If all the elements of the arrays are items

and itemsWithQuantity

are related to each other, you can simply do:



var items    = [{"id": 1,"qty": undefined, "x": "something"}, {"id": 2,"qty": undefined, "x":"another thing"}, {"id": 3,"qty": undefined, "x": "whatever"}],
itemsWithQty = [{"id": 1,"qty": 3}, {"id": 2,"qty": 7}, {"id": 3,"qty": 4}],
result       = items.map((o,i) => Object.assign({},o,itemsWithQty[i]));

console.log(result);
      

Run code


0


source


If it really isn't, you can just assign one array to another, then you can use the built-in . map and find methods .

Example below (although at the end of the day, internally, it still does the cycles you described):

 const res = items
    .map(item =>  Object.assign({}, item,{qty:(itemsWithQuantities.find(iwq => iwq.id === item.id) || {qty:0}).qty}));

      

0


source







All Articles