compare headerObj(field_key) and dataObj(key) and form the result with label from headerObj
const headerObject = [{
label: 'Code',
field_key: 'code'
},
{
label: 'Worked Accounts',
field_key: 'workedAccounts'
},
{
label: 'Contactable Accounts',
field_key: 'contactableAccounts'
},
{
label: 'Taken By',
field_key: 'takenBy'
},
];
const dataObj = [{
"code": "ABCD",
"takenBy": "",
"workedAccounts": 4,
"contactableAccounts": 3,
},
{
"takenBy": "Ram",
"workedAccounts": 2,
"contactableAccounts": 1,
},
{
"takenBy": "krish",
"workedAccounts": 2,
"contactableAccounts": 2,
},
{
"code": "XYZ",
"takenBy": "",
"workedAccounts": 9,
"contactableAccounts": 4,
},
{
"Taken By": "Jack",
"workedAccounts": 5,
"contactableAccounts": 0,
},
{
"Taken By": "krish",
"workedAccounts": 4,
"contactableAccounts": 4,
}
];
const result = [{
"Code": "ABCD",
"Taken By": "",
"Worked Accounts": 4,
"Contactable Accounts": 3,
},
{
"Taken By": "Ram",
"Worked Accounts": 2,
"Contactable Accounts": 1,
},
{
"Taken By": "krish",
"Worked Accounts": 2,
"Contactable Accounts": 2,
},
{
"Code": "XYZ",
"Taken By": "",
"Worked Accounts": 9,
"Contactable Accounts": 4,
},
{
"Taken By": "Jack",
"Worked Accounts": 5,
"Contactable Accounts": 0,
},
{
"Taken By": "krish",
"Worked Accounts": 4,
"Contactable Accounts": 4,
}
];
result = filter(headerObj, el =>
Object.keys(dataObj)?.filter(ele => ele === el.field_key && {[el.field.key]: ele[field.key));
CodePudding user response:
You have and errors in your example objects, but I think this is what you need:
const map = headerObject.reduce((acc, item) => ({...acc, [item.field_key]: item.label}), {});
dataObj.reduce((acc, item) => [
...acc,
Object.keys(item).reduce((curr, key) => ({ ...curr, [map[key]]: item[key] }), {})
], []);
at first you need create a map for easy compare keys and values and then map it. Hope this helps.
CodePudding user response:
const headerArray = [
{
label: 'Code',
field_key: 'code',
},
{
label: 'Worked Accounts',
field_key: 'workedAccounts',
},
{
label: 'Contactable Accounts',
field_key: 'contactableAccounts',
},
{
label: 'Taken By',
field_key: 'takenBy',
},
];
// This is how your header array should be structured
// in the first place
const headerMap = headerArray.reduce((acc, { label, field_key }) => {
acc[field_key] = label;
return acc;
}, {});
const dataArray = [
{
code: 'ABCD',
takenBy: '',
workedAccounts: 4,
contactableAccounts: 3,
},
{
takenBy: 'Ram',
workedAccounts: 2,
contactableAccounts: 1,
},
{
takenBy: 'krish',
workedAccounts: 2,
contactableAccounts: 2,
},
{
code: 'XYZ',
takenBy: '',
workedAccounts: 9,
contactableAccounts: 4,
},
{
takenBy: 'Jack',
workedAccounts: 5,
contactableAccounts: 0,
},
{
takenBy: 'krish',
workedAccounts: 4,
contactableAccounts: 4,
},
];
const result = dataArray.map((obj) => {
return Object.fromEntries(Object.keys(obj).map((key) => [headerMap[key], obj[key]]));
});
console.log(result);