1

I have the following array structure:

  const mockData = [
    {
      text: 'Text1',
      data: [
        { field: '1' },
        { field: '2' },
        { field: '3' },
        { field: '4' },
        { field: '5' },
        { field: '6' }
      ]
    },
      {
      text: 'Text1',
      data: [
        { field: '1' },
        { field: '2' },
        { field: '3' },
        { field: '4' },
      ]
    }
  ];

I need to splice(0, 3) a nested data array.

Here's what I tried so far, but I need to get the same output as the input array with sliced data:

  const mockData = [
    {
      text: 'Text1',
      data: [
        { field: '1' },
        { field: '2' },
        { field: '3' },
        { field: '4' },
        { field: '5' },
        { field: '6' }
      ]
    },
      {
      text: 'Text1',
      data: [
        { field: '1' },
        { field: '2' },
        { field: '3' },
        { field: '4' },
      ]
    }
  ];


const slicedArray = mockData.reduce((accumulator, arr) => {
  const spliceData = arr.data.splice(0, 3);

  accumulator.push(spliceData);

  return accumulator;
}, []);


console.log(slicedArray)

What's the simplest way to achieve it? Thank you!

1
  • 2
    please add the wanted result. btw, splice mutates the array. Commented Mar 31, 2020 at 14:31

1 Answer 1

2

You may use array .map() method:

const mockData = [{text:"Text1",data:[{field:"1"},{field:"2"},{field:"3"},{field:"4"},{field:"5"},{field:"6"}]},{text:"Text1",data:[{field:"1"},{field:"2"},{field:"3"},{field:"4"}]}];

const slicedArray = mockData.map(d => ({...d, data: d.data.slice(0, 3)}))
console.log(slicedArray)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.