Jonathan Samson
Jonathan Samson

Reputation: 3

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.

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.

Upvotes: 0

Views: 28

Answers (2)

Event_Horizon
Event_Horizon

Reputation: 707

Ok after comments I re-read question I think you are trying to make a new OBJECT not a new ARRAY (curly braces are an object).

So with your code to do an OBJECT deep copy, then change the inside array, it will look like:

export const someList = {
  something1: 'some string 1',
  someArr: [
    {
      item: 'item 1',
      },
    },
    {
      item: 'item 2',
      },
    },
    {
      item: 'item 3',
      },
    ],
 something2: {
    some: 'some string 2'
  },
};
let newList=JSON.parse(JSON.stringify(someList));
newList.someArr=newList.someArr.slice(0,2);

Upvotes: 0

Mani
Mani

Reputation: 290

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)

Upvotes: 0

Related Questions