-1

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.

4

2 Answers 2

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]
}));
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.