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 adjust only part of an array, but other parts keep the same?

this is my array

    export const someList = {
      something1: 'some string 1',
      someArr: [
        {
          item: 'item 1',
          },
        },
        {
          item: 'item 2',
          },
        },
        {
          item: 'item 3',
          },
        ],
     something2: {
        some: 'some string 2'
      },
    };

Ok, so what I am trying to achieve is to construct a new array that would look like this:

export const newList = {
  something1: 'some string 1',
    someArr: [
            {
              item: 'item 1',
              },
            },
            {
              item: 'item 2',
              },
            ],
         something2: {
            some: 'some string 2'
          },
        };

So everything remains the same, except that newList takes only first two items from someArr.

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

I have tried this and it works correctly, but I don’t know how to keep "outer" parts in new array (something1 and something2).

const newList = someList.someArr.slice(0, 2)

How can I construct a new array, keeping what I want, but still slicing the items from deeper nested array?

Thanks.

>Solution :

What Event_Horizon answered is correct.

Another way of creating new Object:

const someList = {
      something1: 'some string 1',
      someArr: [
        {
          item: 'item 1',
        },
        {
          item: 'item 2',
        },
        {
          item: 'item 3'
        }
     ],
     something2: {
        some: 'some string 2'
     },
};

let newList={...someList,someArr:someList.someArr.slice(0,2)}
    
console.log(newList)
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