filter object by key and its items

22,546

Array#filter is expecting a boolean value as return value, you might use this

let myKeys = Object.keys(data).filter(key => key == vm.system_id);

for getting the keys and then render a new object with the given keys.

To get all items in a single array, you could collect them with

let result = myKeys.reduce((r, k) => r.concat(data[k]), []);
Share:
22,546
hauge
Author by

hauge

Updated on August 23, 2020

Comments

  • hauge
    hauge over 3 years

    I have an object that I would like to filter it's keys..

    Im trying to filter the object by an ID, like so:

    let myKeys = Object.keys(data).filter(function(key) {
            //console.log(data[key]);
            if(parseInt(key) === parseInt(vm.system_id)) {
                return data[key];
            }
        });
    
        console.log(myKeys);
    

    This works, partialy - im getting the key, however, im not getting all the data/items under this item im filtering out

    The object im filtering is one similar to this one:

    {
    "646": [{
            "id": 52144,
            "timestamp": "2017-08-17T14:10:23Z",
            "type": "alarm",
            "code": 210,
            "title": "",
            "description": "",
            "remedy": "",
            "appeared": "2017-08-17T14:10:09Z",
            "disappeared": null,
            "acknowlegded": null,
            "solved": null,
            "system_name": "CG-MX19D7K5C1",
            "system_id": 646,
            "system_device_id": 458,
            "stream": "cu351.alarm_code"
        }
    ],
    "693": [{
            "id": 51675,
            "timestamp": "2017-08-16T13:59:55Z",
            "type": "alarm",
            "code": 215,
            "title": "",
            "description": "",
            "remedy": "",
            "appeared": "2017-08-16T13:59:57Z",
            "disappeared": null,
            "acknowlegded": null,
            "solved": null,
            "system_name": "Demo 07122016",
            "system_id": 693,
            "system_device_id": 371,
            "stream": "cu351.alarm_code"
        }, {
            "id": 51677,
            "timestamp": "2017-08-16T13:59:57Z",
            "type": "alarm",
            "code": 214,
            "title": "",
            "description": "",
            "remedy": "",
            "appeared": "2017-08-16T13:59:59Z",
            "disappeared": null,
            "acknowlegded": null,
            "solved": null,
            "system_name": "Demo 07122016",
            "system_id": 693,
            "system_device_id": 371,
            "stream": "cu351.alarm_code"
        }
    ]
    

    }

  • hauge
    hauge over 6 years
    Not quite, this still just returns an array with the key ['693'] - But not giving me all the data under this item
  • Nina Scholz
    Nina Scholz over 6 years
    right, you need another loop please add an example and what you expect.