I have a heavily nested object which looks like this:
data = [{
id: 1,
tables: {
headers: [
{headerName: 'First Name',
values: [
{id: 1, text_value: 'John', unique_id: '3UPYR2'}
{id: 2, text_value: 'Nick', unique_id: 'WKKHCM'}
]},
{headerName: 'Last Name',
values: [
{id: 1, text_value: 'Doe', unique_id: '3UPYR2'}
{id: 2, text_value: 'Smith', unique_id: 'WKKHCM'}
]}
]
}
}]
What I want to do is filter out this object but query it on the unique_id attribute for each header so that I can create an object like so:
data = [{
id: 1,
tables: {
headers: [
{headerName: 'First Name',
values: [
{id: 1, text_value: 'John', unique_id: '3UPYR2'}
]},
{headerName: 'Last Name',
values: [
{id: 1, text_value: 'Doe', unique_id: '3UPYR2'}
]}
]
}
}]
I tried implementing the solution on this post (https://stackoverflow.com/questions/56371728/how-can-i-filter-nested-objects-and-arrays-with-javascript#:~:text=Here%20nested%20some%20is%20used%20to) but this just returns the original object.
I updated this implementation like so:
let filetered = data.filter(rec => {
let final = rec.table.some(({headers}) => headers.some(({values}) => values.some(({unique_id}) => unique_id === myUniqueId)))
return final
})
Not entirely sure how this is working or what is going wrong here.
>Solution :
Loop through all the header and filter its values property.
const data = [{
id: 1,
tables: {
headers: [
{headerName: 'First Name',
values: [
{id: 1, text_value: 'John', unique_id: '3UPYR2'},
{id: 2, text_value: 'Nick', unique_id: 'WKKHCM'}
]},
{headerName: 'Last Name',
values: [
{id: 1, text_value: 'Doe', unique_id: '3UPYR2'},
{id: 2, text_value: 'Smith', unique_id: 'WKKHCM'}
]}
]
}
}]
const unique_id = "3UPYR2";
data.forEach(d =>
d.tables.headers.forEach(h =>
h.values = h.values.filter(v => v.unique_id == unique_id)))
console.log(data);