Home > Software engineering >  How to limit an array field in javascript object to a certain length
How to limit an array field in javascript object to a certain length

Time:05-07

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'
        }
    ]
}

CodePudding user response:

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}
  • Related