[Solved] How to map an object as per key and value using JavaScript?


You could take an array for the wanted groups and related keys and take an iterative and recursive approach.

var data = [{ _id: "5c407834953d7f420d56f866", allocated_to: "FIELD", zone: "NORTH", state: "DELHI", location: "NEW DELHI", customer_name: "REET INFOTECH", bank_name_of_customer: "YES BANK", cl_contract_id: "LAI-00016881", lk_loan_account_id: "LK0000015094", front_end_manager_name: "SONAL", area_collection_manager: "ASHIS JENA", installment_date: "", collection_manager: "" }, { _id: "5c407834953d7f420d56f867", allocated_to: "FIELD", zone: "NORTH", state: "DELHI", location: "Sree Nagar", customer_name: "REET", bank_name_of_customer: "Corporate BANK", cl_contract_id: "LAI-00016881", lk_loan_account_id: "LK0000015094", front_end_manager_name: "SONAL", area_collection_manager: "ASHIS JENA", installment_date: "", collection_manager: "" }, { _id: "5c407834953d7f420d56f868", allocated_to: "FIELD", zone: "EAST", state: "Odisha", location: "Bhubaneswar", customer_name: "REET", bank_name_of_customer: "PNB BANK", cl_contract_id: "LAI-00016881", lk_loan_account_id: "LK0000015094", front_end_manager_name: "SONAL", area_collection_manager: "ASHIS JENA", installment_date: "", collection_manager: "" }, { _id: "5c407834953d7f420d56f890", allocated_to: "FIELD", zone: "EAST", state: "Assam", location: "Gawhati", customer_name: "REET", bank_name_of_customer: "SBI BANK", cl_contract_id: "LAI-00016881", lk_loan_account_id: "LK0000015094", front_end_manager_name: "SONAL", area_collection_manager: "ASHIS JENA", installment_date: "", collection_manager: "" }],
    groups = [
        ['zone_list', 'zone'],
        ['state_list', 'state'],
        ['location_list', 'location'],
        ['task_list', '_id', 'front_end_manager_name', 'area_collection_manager', 'collection_manager'],
        ['loan_accounts_assigned', 'lk_loan_account_id', 'allocated_to', 'cl_contract_id', 'customer_name', 'bank_name_of_customer']
    ],
    result = data.reduce((r, o) => {
        groups.reduce((t, [group, ...keys]) => {
            var temp = (t[group] = t[group] || []).find(p => o[keys[0]] === p[keys[0]]);
            if (!temp) {
                temp = Object.assign({}, ...keys.map(k => ({ [k]: o[k] })));
                t[group].push(temp);
            }
            return temp;
        }, r);
        return r;
    }, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

5

solved How to map an object as per key and value using JavaScript?