TypeScript- How to add a Key Value pair to each object in an Array?

15,173

Solution 1

What's wrong with your code is that idx will be the object not the index as you are using for...of. Use a simple regular for like:

for(let idx = 0; idx < data.length; idx++) {
    data[idx].date = dates[idx];
}

Or use forEach to loop one of the arrays and use the index it provides to get the value from the other array:

data.forEach((obj, i) => obj.date = dates[i]);

Solution 2

const result = data.map(({ name, age }, index) => ({ name, age, date: dates[index] }));

just map the array to the result.

Solution 3

Something like that:

    let dates = ["10-12-18", "10-13-18", "10-14-18"];

    let objs = [{"name":"One",
     "age": "4"},

     {"name":"Two",
     "age": "5"},

    {"name":"Three",
     "age": "9"}
    ]

    const result = objs.map((item, index) => {
        item.Date = dates[index];
        return item;
    });

console.log(result);
Share:
15,173
LaurenAH
Author by

LaurenAH

Updated on June 27, 2022

Comments

  • LaurenAH
    LaurenAH almost 2 years

    I have an array of dates and an array of objects. I'd like to add the dates to the array of objects as a key value pair {"Date": "10-12-18"}.

    dates:

    ["10-12-18", "10-13-18", 10-14-18"]
    

    data:

    [
       {"name":"One", "age": "4"},
       {"name":"Two", "age": "5"},
       {"name":"Three", "age": "9"}
    ]
    

    I want something like...

    [
        {"name":"One", "age": "4", "Date": "10-12-18"},
        ....
    

    How can I do this in TypeScript? I'm used to normal JavaSCript and can't get it right.

    Something I have so far:

    for (let idx of data){
       data[idx].date = dates[idx] 
    }
    

    Thanks!!

    • jonatjano
      jonatjano over 5 years
      do it like in JS, typescript should compile vanilla JS without problem
    • smac89
      smac89 over 5 years
      Can you post the code you were using? Doing this in Javascript should be no different from doing it in Typescript. So if it wasn't working in JS, you are probably doing something wrong and typescript won't fix that
    • T.J. Crowder
      T.J. Crowder over 5 years
      "I'm used to normal JavaSCript and can't get it right." What have your non-right solutions looked like?
    • LaurenAH
      LaurenAH over 5 years
      Edited with my attempt
  • LaurenAH
    LaurenAH over 5 years
    Perfect and concise, thank you. I need to get the hang of transitioning into TypeSCript more. it's good to see the two things side by side!
  • ibrahim mahrir
    ibrahim mahrir over 5 years
    @LaurenAH Actually this is still valid javascript as well.
  • ibrahim mahrir
    ibrahim mahrir over 5 years
    BTW, using map is totally unecessary here as you are altering the original objects so a simple forEach will do. console.log(objs); to see what I'm talking about.