I am working with two objects, data and map, in which I need to update the keys of the data object with the text value of the map object based on the key of data matching the value of the datafield key within the map object.
data = [{
1230c9299007b07bf73bb396: "Current",
5900c9299007b07bf73bb3a0: "Will",
5900c9299007b07bf73bb39f: "Johnson"
}, {
1230c9299007b07bf73bb396: "Current",
5900c9299007b07bf73bb3a0: "Donna",
5900c9299007b07bf73bb39f: "Sampson"
}, {
1230c9299007b07bf73bb396: "Past",
5900c9299007b07bf73bb3a0: "Frank",
5900c9299007b07bf73bb39f: "Lloyd"
}];
map = [{
dataField: "1230c9299007b07bf73bb396",
text: "Customer Type"
}, {
dataField: "5900c9299007b07bf73bb3a0",
text: "First Name"
}, {
dataField: "5900c9299007b07bf73bb39f",
text: "Last Name"
}];
Expected result:
result = [{
"Customer Type": "Current",
"First Name": "Will",
"Last Name": "Johnson"
}, {
"Customer Type": "Current",
"First Name": "Donna",
"Last Name": "Sampson"
}, {
"Customer Type": "Past",
"First Name": "Frank",
"Last Name": "Lloyd"
}];
I have attempted with the following code only to find the two objects merge and do not update any of the object keys as expected:
let items = Object.keys(data).map((key) => {
const newKey = map[key] || key;
return { [newKey] : data[key] };
});
1230c9299007b07bf73bb396, etc. need to be in quotes.)Object.keys(data)are the indices of the array. Notice your map is used on the array. I think you meant to loop through the data array and then for each object compare the key