skip to Main Content

I have 2 arrays with different lengths and the number of items in each array is dynamic. I want to create the finalArray. How can I do that?
I want to add each item in array1 to all objects of array2 as key and an empty array as value.

 const array1 = [7665,7666]
 const array2 = [
{
    "id": 1,
    "name": "user-1",
},
{
    "id": 2,
    "name": "user-2", 
},
{
    "id": 3,
    "name": "user-3",
},
  ]

 const finalArray = [
    {
      7665: [],
      7666: [],
      users: 'user-1',
    },
    {
      7665: [],
      7666: [],
      users: 'user-2',
    },
    {
      7665: [],
      7666: [],
      users: 'user-3',
    }
  ]

2

Answers


  1. Here you go:

    const array1 = [7665, 7666];
    const array2 = [{
        "id": 1,
        "name": "user-1",
      },
      {
        "id": 2,
        "name": "user-2",
      },
      {
        "id": 3,
        "name": "user-3",
      },
    ];
    
    const result = array2.map(({ id, name }) => ({ 
      ...array1.reduce((acc, cur) => ({ 
        ...acc, 
        [cur]: [] 
      }), {}), 
      users: name 
    }))
    
    console.log(result)

    The map creates one object per user from array2. The reduce converts each number in array1 to a key on the final user object.

    Login or Signup to reply.
  2. try that

    const array1 = [7665, 7666];
    const array2 = [{
        "id": 1,
        "name": "user-1",
      },
      {
        "id": 2,
        "name": "user-2",
      },
      {
        "id": 3,
        "name": "user-3",
      },
    ];
    let finalArray = [];
    for (let i = 0; i < array2.length; i++) {
      let obj = {};
      obj[array1[0]] = [];
      obj[array1[1]] = [];
      obj['users'] = array2[i].name;
      finalArray.push(obj);
    }
    console.log(finalArray);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search