Test Human
Test Human

Reputation: 31

Push object into array without key in javascript

I want to push my object without a key in my javascript array. Right now the issue is I psuh my object in the array, but I add extra key 0,1,2 ... I don't want that key. Is there any solution for that? Here I add the code that I implemented.

let newArr = [];
let myId = data['id'];
var key = myId;
var obj = {};
myobj[key] = {
  data: "testdata"
};
newArr.push(myobj);

The above code generates output like below. I don't want that 0 key in my array

0: { 
    260: {
        data: 'testdata'
    },
}

Upvotes: 0

Views: 3704

Answers (2)

Vasile Radeanu
Vasile Radeanu

Reputation: 906

Try this

newArr.push(...myobj);

Upvotes: 1

Scotty Jamison
Scotty Jamison

Reputation: 13209

It's hard to tell what you're wanting, but I expect you don't want to be using an array here at all? You just want a single object that contains all of your key-value pairs?

e.g. something like this:

const data = { id: 1234 };

let myId = data['id'];
var key = myId;
var myobj = {};
myobj[key] = {
  data: "testdata"
};

console.log(myobj);

// You can then add more data
myobj[2345] = {
  data: "more test data"
};

console.log(myobj);

// Example Property Access
console.log(myobj[2345])

Upvotes: 2

Related Questions