Home > Net >  How to adjust only part of an array, but other parts keep the same?
How to adjust only part of an array, but other parts keep the same?

Time:12-02

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.

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
  • Related