Search code examples
javascriptjsonchakram

Fetching records from inside a JSON Object inside an Array


I have an API response coming in this format.

 [{
 "response_data": {
    "0":{
    "id" : 0,
    "office" : "India",
    "type" : 'Perm'
    },
    "1":{
    id : 0,
    "office" : "America",
    "type" : 'Perm'
    },
    "2":{
    id : 0,
    "office" : "Europe",
    "type" : 'Contract'
    },
    "2":{
    id : 0,
    "office" : "Latin America",
    "type" : 'Contract'
    }

    }}]

I am trying to get all the office where the type is Contract. I have the json response saved in a variable like - using Chakram as

var response_json = t.body[0].response_data;

which gives me correct response in the console.log as

       "0":{
    "id" : 0,
    "office" : "India",
    "type" : 'Perm'
    },
    "1":{
    id : 0,
    "office" : "America",
    "type" : 'Perm'
    },
    "2":{
    id : 0,
    "office" : "Europe",
    "type" : 'Contract'
    },
    "2":{
    id : 0,
    "office" : "Latin America",
    "type" : 'Contract'
    }

Now how to get to the corresponding keys in inside the json and extract the information required. I tried this but it returns undefined

var length = Object.keys(response_json).length;
for(var i = 0; i<= length;i++){
console.log(response_json.i) //returns undefined
 console.log((Object.keys(response_json)).id); //returns undefined.
}

I know that this can be solved using filter method if the response was an array, but how can I do the same operation in JSON object? I am looking for an optimized solution because the API returns almost 5000 objects. If this question has already been asked, provide reference since I was not able to find any on SO.


Solution

  • If you want to do this with filter method then a workaround would be to add a property length then using Array.from like below. Then you can use Array.prototype.filter method.

    let o = {
        '0': {
            id: 0,
            "office": "India",
            "type": 'Perm'
        },
        '1': {
            id: 0,
            "office": "America",
            "type": 'Perm'
        },
        '2': {
            id: 0,
            "office": "Europe",
            "type": 'Contract'
        }
    };
    
    o.length = Object.keys(o).length;
    let a = Array.from(o);
    
    let r = a.filter(({ type }) => type == 'Contract');
    console.log(r);