The task is to slice a nested array by data property.
I have the following array structure:
const mockData = [
{
text: 'Text1',
data: [
{ field: '1' },
{ field: '2' },
{ field: '3' },
{ field: '4' },
{ field: '5' },
{ field: '6' }
]
},
{
text: 'Text2',
data: [{ field: '1' }, { field: '2' }, { field: '3' }, { field: '4' }]
}
];
Here's the method I use:
const sliceArray = mockData => mockData.map(d => ({...d, data: d.data.slice(0, 3)}))
It goes through all nested objects and slice array by data property, but how can I do it for a specific nested object instead of all of them?
I'd like to use text property as a key.
So, if I pass Text1 to a method - data property in the first object only should be sliced and the output should be:
const mockData = [
{
text: 'Text1',
data: [{ field: '1' }, { field: '2' }, { field: '3' }]
},
{
text: 'Text2',
data: [{ field: '1' }, { field: '2' }, { field: '3' }, { field: '4' }]
}
];
If I pass 'Text2':
const mockData = [
{
text: 'Text1',
data: [
{ field: '1' },
{ field: '2' },
{ field: '3' },
{ field: '4' },
{ field: '5' },
{ field: '6' }
]
},
{
text: 'Text2',
data: [{ field: '1' }, { field: '2' }, { field: '3' }]
}
];
What can be the solution? Thank you!
Text1only in object with a 'text' = Text1,dataarray should be sliced. Other objects should remain.