Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to limit an array field in javascript object to a certain length

I know this may a simple problem but I have a the following javascript object:

const categories = {
    title: 'cat1',
    contents: [
        {
            name: 'cont1'
        },
        {
            name: 'cont2'
        },
        {
            name: 'cont3'
        }
    ]
}

How can a transform this categories object so it has only 2 contents element as an example?

const transformedCategories = {
    title: 'cat1',
    contents: [
        {
            name: 'cont1'
        },
        {
            name: 'cont2'
        }
    ]
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A couple of ways to do it:

const transformedCategories = {
  title: categories.title,
  contents: categories.contents.slice(0,2) // you can also use splice here
}

Another, slightly cheeky way:

const contents = [...categories.contents];
contents.length = 2;
const transformedCategories = {...categories, contents}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading