Home > OS >  pull object out of array
pull object out of array

Time:08-07

Now the result of files.splice(index, 1) is an array and I wanted to push the result of files.splice(index, 1) to splicedFiles as an object and not an array of object since splicedFiles is already an array, so currently my code resulted into a 2 dimensional array which I don't want.

Is there a way that I can push files.splice(index, 1) as an object and not as an array of object? so that it would be push as an object to splicedFiles and not as an array of objects.

So basically I want to pull out the object first from files.splice(index, 1) and then push it to splicedFiles.

So currently this is the result, 2 dimension. which is wrong enter image description here

#sample files format

const arr = [
    {
        "id": 290,
        "size": 50461,
    },
]

#ts-code

splicedFiles = new Array();
removeFile(files: any, index: number) {
  return this.splicedFiles.push(files.splice(index, 1));
}

CodePudding user response:

shift() (doc) which destructively remove (and return) the first element of an array. So just push the result of shift.

let array = [{ id: 0 }, { id: 1 } ,{ id: 2 }];
let spliced = [];

spliced.push(array.shift());
spliced.push(array.shift());

console.log(array)    // expect id 2
console.log(spliced)  // expect ids 0,1

edit To do this at an arbitrary index, use splice, then dereference the resulting array.

let array = [{ id: 0 }, { id: 1 } ,{ id: 2 }];
 let spliced = []
 
 const moveIndexFromTo = (index, fromArray, toArray) => {
   toArray.push(fromArray.splice(index, 1)[0])
 }

moveIndexFromTo(1, array, spliced)

console.log(array);   // expect ids 0,2
console.log(spliced)  // expect id 1

  • Related