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.
-
"I have tried mapping it..." We'd love to see those attempts! Also, you should start by NOT using curly quotes in code. And after you replace those curly single quotes, you should make a minimal reproducible example stackoverflow.com/help/minimal-reproducible-example. What errors are you seeing when you try?Marc– Marc2023年03月22日 16:22:06 +00:00Commented Mar 22, 2023 at 16:22
-
is that invalid output what you expect? or you meant an array of objects?Chris G– Chris G2023年03月22日 16:31:16 +00:00Commented Mar 22, 2023 at 16:31
-
Does this answer your question? Combine the values of two arrays into objectpilchard– pilchard2023年03月22日 16:43:33 +00:00Commented Mar 22, 2023 at 16:43
-
and Combining two arrays to form a javascript object or How to combine two arrays into an array of objects? or How to create an array of objects from multiple arrayspilchard– pilchard2023年03月22日 16:45:05 +00:00Commented Mar 22, 2023 at 16:45
2 Answers 2
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
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);
answered Mar 22, 2023 at 16:37
protob
3,6211 gold badge11 silver badges24 bronze badges
Comments
lang-js