Home > Enterprise >  Array of objects, remove the array after push, keep objects
Array of objects, remove the array after push, keep objects

Time:04-20

Im trying to push my array of objects into variable, but all i I recieve is Array in Array, or single object.

  myObject = {
          id: id,
          items: [],
          boolean: true,  
        }
    
    myArray = [{1}, {2}, {3}]

I tried myObject.items.push(myArray[0]) but this returns only first object. Without 0 its double array.

What i want is

myObject = {
              id: id,
              items: [{1}, {2}, {3}],
              boolean: true,  
            }

CodePudding user response:

What you're going to want to do here is set the entire array as the new value like this:

myObject.items = myArray

If you want to take the immutable approach then you can copy it like this:

myObject.items = [...myArray]

CodePudding user response:

you can use this

myObject.items.push(...myArray)

CodePudding user response:

As Andreas commented another solution is to use concat. Concat is similar to push. But it doesn't actually change the array it returns a new one.

const x = []
console.log(x.concat(3)) // prints [3]
console.log(x) // prints []

This behavior is often desired as it prevents "side effects" from occurring

It also doesn't just append items to an array, it only does this if the item is not an array. If it is an array it will merge the two arrays

const x = [1,2,3]
console.log(x.concat([4,5,6]) // prints [1,2,3,4,5,6]

so a solution here is

myObject.items = myObject.items.concat(myArray)
  • Related