javascriptarraysvuejs2array-pusharray-reduce

JS: How to combine Object from two different arrays into one Array/Object


If have two arrays (content & ids) which i need to combine in one array (combined).

First Array:

let content = [
  { "Name": "Max Mustermann" },
  { "Name": "Berta Beispiel" },
  { "Name": "Zacharias Zufall" }
]

Second Array:

let ids = [
  "12345678-1", 
  "12345678-2", 
  "12345678-3"
]

Which should combined look like this:

let combined = [
  {
    "Name": "Max Mustermann",
    "id": "12345678-1"
  },
    {
    "Name": "Berta Beispiel",
    "id": "12345678-2"
  },
    {
    "Name": "Zacharias Zufall",
    "id": "12345678-3"
  }
]

I tried different things from push, reduce, map.... but nothing worked: :(


Solution

  • Depending on what you need, something as simple as this could work. Note: it modifies the original content array.

    let content = [
      { "Name": "Max Mustermann" },
      { "Name": "Berta Beispiel" },
      { "Name": "Zacharias Zufall" }
    ]
    
    let ids = [
      "12345678-1", 
      "12345678-2", 
      "12345678-3"
    ];
    
    for(let i=0;i<content.length;i++) {
      content[i].id = ids[i] || null;
    }
    
    console.log(content);

    If you need to create a new object + new array from the two, you can use

    const content = [
      { "Name": "Max Mustermann" },
      { "Name": "Berta Beispiel" },
      { "Name": "Zacharias Zufall" }
    ]
    
    const ids = [
      "12345678-1", 
      "12345678-2", 
      "12345678-3"
    ];
    
    const merged = content.map((c, index) => ({id: ids[index] || null, ...c}));
    console.log(merged);

    It really depends more on you and the context of the situation.

    Edit

    I'd feel like I wasn't doing my duty if I didn't mention that in Javascript the difference between let and const in reference to arrays or objects is a bit muddled.

    The following is perfectly valid JS with the const declaration:

    const items = [];
    items.push(1,2,3);
    console.log(items); // 1, 2, 3
    

    This is because the const refers to some more complicated information that you can look up as you understand more of the language itself. In the future, however, the basic thing you need to ask yourself when determining whether or not you should use const or let is this:

    Will I need to totally reassign the variable at some point? e.g.

    arr = [1,2,3]; 
    /// code later on;
    arr = [5,6,7];
    

    If so, use let. But if your code looks more like

    arr = [1,2,3];
    // other stuff
    arr.push(4,5,6);
    arr.pop();
    arr.sort((a,b) => a-b);
    

    Then you are likely OK with using const.

    I know this isn't the best clarification, but speaking more in depth would about it might cause more confusion since I don't know your level of programming knowledge.