Search code examples
javascriptarrayslodash

How to name Values in array by values in different array?


I have two arrays:

The first contains unique names of fields in a nested array:

[0][0]:Name1
[0][1]:Name2
[0][2]:Name3
etc.

The second contains multiple items with values in a nested array like this:

[0][0] XYZ
[0][1] XYZA
[0][2] XYZ2
[1][0] XYZaa
[1][1] XYZas
[1][2] XYA
etc

What I want to do is to merge it and name it in this way:

[0] Name1: XYZ
[0] Name2: XYZA
[0] Name3: XYZ2
[1] Name1: XYZaa
[1] Name2: XYZas
[1] Name3: XYA

To achieve this I first attempted the following:

var mergedArr = name.concat(data);

That works fine, however I believe I can also use lodash to get closer to what I want:

_.merge(name, data)

and should work fine too.

I was trying to name it by using

_.zipObject

Yet it doesn't work the way I would like

I was trying few options with zip, zipObject, yet non of it gave me expected output.

Edit1: how I created arrays:

    $("#T1020 tr").each(function(x, z){
    name[x] = [];
    $(this).children('th').each(function(xx, zz){
           name[x][xx] = $(this).text();

      });

})

    $("#T1020 tr").each(function(i, v){
        data[i] = [];
        $(this).children('td').each(function(ii, vv){
            data[i][ii] = $(this).text();

      });
   })

Solution

  • If I understand your question correctly, you're wanting to zip array1 and array2 into a single array where:

    • each item of the result array is an object
    • the keys of each object are values of array1[0], and
    • the values of each key corresponding nested array of array2

    To produce the following:

    [
     {
      "name1": "xyz",
      "name2": "xyza",
      "name3": "xyz2"
     },
     {
      "name1": "xyzaa",
      "name2": "xyzas",
      "name3": "xya"
     }
    ]
    

    This can be achieved without lodash; first map each item of array2 by a function where array1[0] is reduced to an object. The reduced object is composed by a key that is the current reduce item, and a value that is taken from the indexed value of the current map item:

    const array1 = [
      ['name1', 'name2', 'name3']
    ]
    
    const array2 = [
      ['xyz', 'xyza', 'xyz2'],
      ['xyzaa', 'xyzas', 'xya']
    ]
    
    
    const result = array2.map((item) => {
    
      /* Reduce items of array1[0] to an object
      that corresponds to current item of array2 */
      return array1[0].reduce((obj, value, index) => {
    
        return { ...obj,
          [value]: item[index]
        };
      }, {});
    
    });
    
    console.log(JSON.stringify(result, null, ' '));