Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

petritr's avatar
Level 15

filter json object by keys

I need to filter json object by keys in js:

0: {id: "device_id.0", value: Array(1)}
1: {id: "device_id.1", value: Array(1)}
2: {id: "ip_address.0", value: Array(1)}
3: {id: "ip_address.1", value: Array(1)}

I need to filter it by keys if id key is 0 push to device 0 I need to achieve the following :

device.0 {
{id: "device_id.0", value: Array(1)}
{id: "ip_address.0", value: Array(1)}
}
device.1 {
{id: "device_id.1", value: Array(1)}
{id: "ip_address.1", value: Array(1)}
}
0 likes
3 replies
sustained's avatar

You need to use a for loop and iterate over every entry in the array.

You need to use String.prototype.split to get the ID.

Example: "device_id.0".split('.') would give us ['device_id', '0'].

You need to dynamically create a new object with that.

Does that help? Let us know if you get stuck.

1 like
petritr's avatar
Level 15

@sustained i have an problem:

this works partly not perfect

                var new_arr = [];
                for (i = 0; i <= error.length; i++ ) {
                    if (error[i].id[error[i].id.length - 1] == error[i].id[error[i].id.length - 1]) {
                        new_arr.push({ device: error[i].id[error[i].id.length - 1], id: error[i].id, value: error[i].value });
                        console.log(new_arr);

                    }
                }

I grab the last character with error[i].id[error[i].id.length - 1] but this is not working properly.

I got Uncaught TypeError: Cannot read property 'id' of undefined how can i make this better ?

Please or to participate in this conversation.