I am trying to make a function that maps the data2 object value to the name of the data1.
I tried to iterate data2 object2 with data1 but it is not working properly. I am able to map them but not getting the value of data1 when it is not there in data2.
Is there any way I can map properly to get the desired output mentioned in the code?
let data1 = {
attributes: [{
Id: 'test1',
Name: 'Test1',
Type: 'date'
},
{
Id: 'test2',
Name: 'Test2',
Type: 'string'
},
{
Id: 'test3',
Name: 'Test3',
Type: 'string'
},
{
Id: 'test4',
Name: 'Test4',
Type: 'boolean'
}
]
};
let data2 = {
value: [{
test1: '10-12-2021',
test2: '4'
},
{
test3: '3',
test4: true
},
{
test1: '12-12-2023',
test3: '42'
}
]
};
//output
let ouput = {
rows: [{
Test1: '10/12/2021',
Test2: '4',
Test3: '',
Test4: ''
},
{
Test1: '',
Test2: '',
Test3: '3',
Test4: 'Y'
},
{
Test1: '12/12/2023',
Test2: '',
Test3: '42',
Test4: ''
}
]
};
//function
function mapper(data1, data2) {
let formattedValue = [];
data2.value.forEach(val => {
let data = {};
for (let prop in val) {
let name;
const filter = data1.attributes.filter(el => el.Id === prop)[0];
if (filter) {
name = filter.Name;
switch (filter.Type) {
case 'boolean':
data[name] =
val[prop] === true ? 'Y' : val[prop] === false ? 'N' : '';
break;
case 'date':
data[name] = new Date(val[prop]).toLocaleDateString();
break;
default:
data[name] = val[prop];
break;
}
}
}
formattedValue.push(data);
});
return formattedValue;
}
console.log(mapper(data1, data2));same if I pass data2 as empty value I am looking to get below output
let data1 = {
attributes: [
{
Id: 'test1',
Name: 'Test1',
Type: 'string'
},
{
Id: 'test2',
Name: 'Test2',
Type: 'string'
},
{
Id: 'test3',
Name: 'Test3',
Type: 'string'
},
{
Id: 'test4',
Name: 'Test4',
Type: 'boolean'
}
]
};
let data2 = {
value: [
]
};
//output
let ouput = {
rows: [
{
Test1: '',
Test2: '',
Test3: '',
Test4: ''
},
]
};from JavaScript: How to map two objects to get the output which map the Id of first object to the name of other object?
No comments:
Post a Comment