skip to Main Content

Can someone please help me resolve below object in javascript? I would be so grateful for your help.

//Current Object:
Data: {
    Name: [‘A’, ‘B’, ‘C’, ‘D’],
    Id: [1, 2, 3, 4]
      }
//Expected output: 

Data: {
      {Name: ‘A’, Id: 1},
      {Name: ‘B’, Id: 2},
      {Name: ‘C’, Id: 3},
      {Name: ‘D’, Id: 4}
    }

I have tried mapping it with Object.keys() and map() function, but it didn’t help much. I am a beginner at Javascript, looking for someone’s help.

2

Answers


  1. You can’t create an object:

    const Data = {
      { Name: 'A', Id: 1 },
      { Name: 'B', Id: 2 },
      { Name: 'C', Id: 3 },
      { Name: 'D', Id: 4 }
    };
    

    But instead of that you can make an array:

    const Data = [
      { Name: 'A', Id: 1 },
      { Name: 'B', Id: 2 },
      { Name: 'C', Id: 3 },
      { Name: 'D', Id: 4 }
    ];
    

    Example code:

    const data = {
      name: ['A', 'B', 'C', 'D'],
      id: [1, 2, 3, 4]
    }
    
    const mappedData = data.name.map((element, index) => ({
      name: data.name[index],
      id: data.id[index]
    }));
    
    Login or Signup to reply.
  2. You can use helper function with destructuring arguments and .map() like this:

    const obj = {
      Data: {
        Name: ['A', 'B', 'C', 'D'],
        Id: [1, 2, 3, 4]
      }
    };
    
    
    const obj2ArrOfObj = ({ Name, Id }) => Name.map((name, idx) => ({ Name: name, Id: Id[idx] }));
    
    const mappedObj = {
      Data: obj2ArrOfObj(obj.Data)
    };
    
    console.log(mappedObj);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search