0

I haven an json array with nested array objects i want to fetch particular object by key name. I've tried alot but i need some generic solution.

let data = {"role":"http://www.icai.org/xbrl/taxonomy/role/in-ca/DisclosureOfGeneralInformationAboutCompany","facts":{"concept":"in-ca:DisclosureOfGeneralInformationAboutCompanyAbstract","$t":"","facts":[{"concept":"in-ca:DisclosureOfCompanyInformationAbstract","$t":"","facts":[{"concept":"in-ca:NameOfCompany","d2016":"LAKSHMI ENERGY AND FOODS LIMITED"},{"concept":"in-ca:CorporateIdentityNumber","d2016":"L00000CH1990PLC010573"},{"concept":"in-ca:PermanentAccountNumberOfEntity","d2016":"AAACL3147J"},{"concept":"in-ca:AddressOfRegisteredOfficeOfCompany","d2016":"SCO 18  19  1ST FLOOR SECTOR 9 D, MADHYA MARH   CHANDIGARH"},{"concept":"in-ca:TypeOfIndustry","d2016":"Commercial and Industrial"},{"concept":"in-ca:RegistrationDate"},{"concept":"in-ca:CategoryOrSubcategoryOfCompany"},{"concept":"in-ca:WhetherCompanyIsListedCompany"}]},{"concept":"in-ca:DisclosureOfDocumentInformationAbstract","$t":"","facts":[{"concept":"in-ca:DateOfBoardMeetingWhenFinalAccountsWereApproved","d2016":"2016-05-09"},{"concept":"in-ca:PeriodCoveredByFinancialStatements"},{"concept":"in-ca:DateOfStartOfReportingPeriod","d2015":"2014-04-01","d2016":"2015-04-01"},{"concept":"in-ca:DateOfEndOfReportingPeriod","d2015":"2015-03-31","d2016":"2016-03-31"},{"concept":"in-ca:NatureOfReportStandaloneConsolidated","d2016":"Standalone"},{"concept":"in-ca:ContentOfReport","d2016":"Financial Statements"},{"concept":"in-ca:DescriptionOfPresentationCurrency","d2016":"INR"},{"concept":"in-ca:LevelOfRoundingUsedInFinancialStatements","d2016":"Millions"},{"concept":"in-ca:TypeOfCashFlowStatement","d2016":"Indirect Method"},{"concept":"in-ca:DisclosureWebLinkOfCompanyAtWhichAnnualReportIsPlaced"}]},{"concept":"in-ca:DisclosureOfOtherGeneralInformationAbstract","$t":"","facts":[{"concept":"in-ca:DateFromWhichRegisterOfMembersRemainedClosed"},{"concept":"in-ca:DateTillWhichRegisterOfMembersRemainedClosed"},{"concept":"in-ca:NameOfRegistrarAndTransferAgent"},{"concept":"in-ca:AddressAndContactDetailsOfRegistrarAndTransferAgent"},{"concept":"in-ca:WhetherCompanyIsMaintainingBooksOfAccountAndOtherRelevantBooksAndPapersInElectronicForm","d2016":"true"},{"concept":"in-ca:PostalAddressOfPlaceOfMaintenanceOfComputerServersStoringAccountingDataAbstract","facts":[{"concept":"in-ca:CompletePostalAddressOfPlaceOfMaintenanceOfComputerServersStoringAccountingData","d2016":"Lakshmi Energy and Foods Limited Chandigarh-Ludhiana National Highway, at Khamanon, Punjab,"},{"concept":"in-ca:NameOfCityOfPlaceOfMaintenanceOfComputerServersStoringAccountingData","d2016":"Chandigarh-Ludhiana National Highway, at Khamanon, Punjab,"},{"concept":"in-ca:NameOfStateUnionTerritoryOfPlaceOfMaintenanceOfComputerServersStoringAccountingData","d2016":"Punjab"},{"concept":"in-ca:PinCodeOfPlaceOfMaintenanceOfComputerServersStoringAccountingData","d2016":"141801"},{"concept":"in-ca:NameOfDistrictOfPlaceOfMaintenanceOfComputerServersStoringAccountingData","d2016":"Punjab"},{"concept":"in-ca:ISOCountryCodeOfPlaceOfMaintenanceOfComputerServersStoringAccountingData","d2016":"IN"},{"concept":"in-ca:NameOfCountryOfPlaceOfMaintenanceOfComputerServersStoringAccountingData","d2016":"India"},{"concept":"in-ca:PhoneWithSTDISDCodeOfPlaceOfMaintenanceOfComputerServersStoringAccountingData","d2016":"01628-661800"}]},{"concept":"in-ca:ParticularsOfServiceProviderAbstract","$t":"","facts":[{"concept":"in-ca:NameOfTheServiceProvider"},{"concept":"in-ca:InternetProtocolAddressOfServiceProvider"},{"concept":"in-ca:LocationOfTheServiceProvider"},{"concept":"in-ca:WhetherBooksOfAccountAndOtherBooksAndPapersAreMaintainedOnCloud"},{"concept":"in-ca:AddressAsProvidedByTheServiceProvider"}]}]},{"concept":"in-ca:DisclosureOfPrincipalProductOrServicesAbstract","$t":"","facts":[{"concept":"in-ca:TotalNumberOfProductOrServiceCategory"},{"concept":"in-ca:DescriptionOfPrincipalProductOrServicesCategory"},{"concept":"in-ca:DisclosureOfPrincipalProductOrServicesTable"},{"concept":"in-ca:DisclosureOfPrincipalProductOrServicesLineItems","$t":"","facts":[{"concept":"in-ca:ProductOrServiceCategoryITC4DigitCode","d2016_TypesOfPrincipalProductOrServicesAxis_Prod1":"1006"},{"concept":"in-ca:DescriptionOfProductOrServiceCategory","d2016_TypesOfPrincipalProductOrServicesAxis_Prod1":"Rice and Paddy"},{"concept":"in-ca:TurnoverOfProductOrServiceCategory","d2016_TypesOfPrincipalProductOrServicesAxis_Prod1":"8,784,320,000.00"},{"concept":"in-ca:HighestTurnoverContributingProductOrServiceITC8DigitCode","d2016_TypesOfPrincipalProductOrServicesAxis_Prod1":"10061090"},{"concept":"in-ca:DescriptionOfProductOrService","d2016_TypesOfPrincipalProductOrServicesAxis_Prod1":"Rice and Paddy"},{"concept":"in-ca:UnitOfMeasurementOfHighestContributingProductOrService","d2016_TypesOfPrincipalProductOrServicesAxis_Prod1":"kg"},{"concept":"in-ca:TurnoverOfHighestContributingProductOrService","d2016_TypesOfPrincipalProductOrServicesAxis_Prod1":"8,784,320,000.00"},{"concept":"in-ca:QuantityOfHighestContributingProductOrServiceInUom"}]}]}]}}

actually this object has an facts key while i need to fetch data if concept key is matching with the passed key so it should return particular object. if you have any generic solution please share. i have created one solution but that is an dirty one and that may break at some point of time.

const getObj = (data, key, subKey) =>{
let obj = {};
key = `:${key}`;
data.forEach((v)=>{
    if(v.facts){
        if(v.facts.length > 0){
            v.facts.forEach((m)=>{
                if(m.facts){
                    if(m.facts.length > 0){
                        m.facts.forEach((n)=>{
                            if(n.facts){
                                if(n.facts.length > 0){
                                    n.facts.forEach((o)=>{
                                        if(o.concept.includes(key)) {
                                            obj = o;
                                            return true;
                                        }
                                    })
                                }
                                else{
                                    if(n.concept.includes(key)) {
                                        obj = n;
                                        return true;
                                    }
                                }
                            }
                            else {
                                if(n.concept.includes(key)) {
                                    obj = n;
                                    return true;
                                }
                            }
                        })
                    }
                    else{
                        if(m.concept.includes(key)) {
                            obj = m;
                            return true;
                        }
                    }
                }
                else{
                    if(m.concept.includes(key)) {
                        obj = m;
                        return true;
                    }
                }
            })
        }
        else{
            if(v.concept.includes(key)) {
                obj = v;
                return true;
            }
        }
    }
    else{
        if(v.concept == key) {
            obj = v;
            return true;
        }
    }
});

let value = "";
if(obj[`i${subKey}`]) value = obj[`i${subKey}`];
else if(obj[`d${subKey}`]) value = obj[`d${subKey}`];
else if(obj[subKey]) value = obj[subKey];

return value;}

Please help me out with this

5
  • is facts always an array? please add what you request and the result of it. Commented Jun 16, 2021 at 7:11
  • 1
    I have never so many forEach loops nested inside and inside and going deep. Your code needs a lot of cleanups firstly. This code should be slow as of now because taking so much memory. Commented Jun 16, 2021 at 7:12
  • @NinaScholz no it might be object if there is no nested array inside it if facts is nested only then we need to search into deep Commented Jun 16, 2021 at 7:16
  • return true won't terminate the forEach. It will process each item in the array. Commented Jun 16, 2021 at 7:18
  • 1
    Also, please add the inputs and the expected output. You can probably solve this with a simple recursion that traverses the nested object. Commented Jun 16, 2021 at 7:21

1 Answer 1

3

You could take a recursive approach with a short circuit.

const
    find = (object, key, value) => {
        if (!object) return;
        if ((object[key] || '').includes(value)) return object;
        let target;
        [].concat(object.facts).some(o => target = find(o, key, value));
        return target;
    },
    data = { role: "http://www.icai.org/xbrl/taxonomy/role/in-ca/DisclosureOfGeneralInformationAboutCompany", facts: { concept: "in-ca:DisclosureOfGeneralInformationAboutCompanyAbstract", $t: "", facts: [{ concept: "in-ca:DisclosureOfCompanyInformationAbstract", $t: "", facts: [{ concept: "in-ca:NameOfCompany", d2016: "LAKSHMI ENERGY AND FOODS LIMITED" }, { concept: "in-ca:CorporateIdentityNumber", d2016: "L00000CH1990PLC010573" }, { concept: "in-ca:PermanentAccountNumberOfEntity", d2016: "AAACL3147J" }, { concept: "in-ca:AddressOfRegisteredOfficeOfCompany", d2016: "SCO 18  19  1ST FLOOR SECTOR 9 D, MADHYA MARH   CHANDIGARH" }, { concept: "in-ca:TypeOfIndustry", d2016: "Commercial and Industrial" }, { concept: "in-ca:RegistrationDate" }, { concept: "in-ca:CategoryOrSubcategoryOfCompany" }, { concept: "in-ca:WhetherCompanyIsListedCompany" }] }, { concept: "in-ca:DisclosureOfDocumentInformationAbstract", $t: "", facts: [{ concept: "in-ca:DateOfBoardMeetingWhenFinalAccountsWereApproved", d2016: "2016-05-09" }, { concept: "in-ca:PeriodCoveredByFinancialStatements" }, { concept: "in-ca:DateOfStartOfReportingPeriod", d2015: "2014-04-01", d2016: "2015-04-01" }, { concept: "in-ca:DateOfEndOfReportingPeriod", d2015: "2015-03-31", d2016: "2016-03-31" }, { concept: "in-ca:NatureOfReportStandaloneConsolidated", d2016: "Standalone" }, { concept: "in-ca:ContentOfReport", d2016: "Financial Statements" }, { concept: "in-ca:DescriptionOfPresentationCurrency", d2016: "INR" }, { concept: "in-ca:LevelOfRoundingUsedInFinancialStatements", d2016: "Millions" }, { concept: "in-ca:TypeOfCashFlowStatement", d2016: "Indirect Method" }, { concept: "in-ca:DisclosureWebLinkOfCompanyAtWhichAnnualReportIsPlaced" }] }, { concept: "in-ca:DisclosureOfOtherGeneralInformationAbstract", $t: "", facts: [{ concept: "in-ca:DateFromWhichRegisterOfMembersRemainedClosed" }, { concept: "in-ca:DateTillWhichRegisterOfMembersRemainedClosed" }, { concept: "in-ca:NameOfRegistrarAndTransferAgent" }, { concept: "in-ca:AddressAndContactDetailsOfRegistrarAndTransferAgent" }, { concept: "in-ca:WhetherCompanyIsMaintainingBooksOfAccountAndOtherRelevantBooksAndPapersInElectronicForm", d2016: "true" }, { concept: "in-ca:PostalAddressOfPlaceOfMaintenanceOfComputerServersStoringAccountingDataAbstract", facts: [{ concept: "in-ca:CompletePostalAddressOfPlaceOfMaintenanceOfComputerServersStoringAccountingData", d2016: "Lakshmi Energy and Foods Limited Chandigarh-Ludhiana National Highway, at Khamanon, Punjab," }, { concept: "in-ca:NameOfCityOfPlaceOfMaintenanceOfComputerServersStoringAccountingData", d2016: "Chandigarh-Ludhiana National Highway, at Khamanon, Punjab," }, { concept: "in-ca:NameOfStateUnionTerritoryOfPlaceOfMaintenanceOfComputerServersStoringAccountingData", d2016: "Punjab" }, { concept: "in-ca:PinCodeOfPlaceOfMaintenanceOfComputerServersStoringAccountingData", d2016: "141801" }, { concept: "in-ca:NameOfDistrictOfPlaceOfMaintenanceOfComputerServersStoringAccountingData", d2016: "Punjab" }, { concept: "in-ca:ISOCountryCodeOfPlaceOfMaintenanceOfComputerServersStoringAccountingData", d2016: "IN" }, { concept: "in-ca:NameOfCountryOfPlaceOfMaintenanceOfComputerServersStoringAccountingData", d2016: "India" }, { concept: "in-ca:PhoneWithSTDISDCodeOfPlaceOfMaintenanceOfComputerServersStoringAccountingData", d2016: "01628-661800" }] }, { concept: "in-ca:ParticularsOfServiceProviderAbstract", $t: "", facts: [{ concept: "in-ca:NameOfTheServiceProvider" }, { concept: "in-ca:InternetProtocolAddressOfServiceProvider" }, { concept: "in-ca:LocationOfTheServiceProvider" }, { concept: "in-ca:WhetherBooksOfAccountAndOtherBooksAndPapersAreMaintainedOnCloud" }, { concept: "in-ca:AddressAsProvidedByTheServiceProvider" }] }] }, { concept: "in-ca:DisclosureOfPrincipalProductOrServicesAbstract", $t: "", facts: [{ concept: "in-ca:TotalNumberOfProductOrServiceCategory" }, { concept: "in-ca:DescriptionOfPrincipalProductOrServicesCategory" }, { concept: "in-ca:DisclosureOfPrincipalProductOrServicesTable" }, { concept: "in-ca:DisclosureOfPrincipalProductOrServicesLineItems", $t: "", facts: [{ concept: "in-ca:ProductOrServiceCategoryITC4DigitCode", d2016_TypesOfPrincipalProductOrServicesAxis_Prod1: "1006" }, { concept: "in-ca:DescriptionOfProductOrServiceCategory", d2016_TypesOfPrincipalProductOrServicesAxis_Prod1: "Rice and Paddy" }, { concept: "in-ca:TurnoverOfProductOrServiceCategory", d2016_TypesOfPrincipalProductOrServicesAxis_Prod1: "8,784,320,000.00" }, { concept: "in-ca:HighestTurnoverContributingProductOrServiceITC8DigitCode", d2016_TypesOfPrincipalProductOrServicesAxis_Prod1: "10061090" }, { concept: "in-ca:DescriptionOfProductOrService", d2016_TypesOfPrincipalProductOrServicesAxis_Prod1: "Rice and Paddy" }, { concept: "in-ca:UnitOfMeasurementOfHighestContributingProductOrService", d2016_TypesOfPrincipalProductOrServicesAxis_Prod1: "kg" }, { concept: "in-ca:TurnoverOfHighestContributingProductOrService", d2016_TypesOfPrincipalProductOrServicesAxis_Prod1: "8,784,320,000.00" }, { concept: "in-ca:QuantityOfHighestContributingProductOrServiceInUom" }] }] }] } };

console.log(find(data, 'concept', 'foo'));
console.log(find(data, 'concept', 'in-ca:DisclosureOfOtherGeneralInformationAbstract'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.