0

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'
    },
}
3
  • that is an index that's automatically generated by javascript, nothing you can do about it. Commented Feb 16, 2021 at 4:52
  • Then how do you retrieve the value from array? :|, and what sort of output you need? Commented Feb 16, 2021 at 4:52
  • Change var obj = {}; into var myobj = {} and it will work fine. Commented Feb 16, 2021 at 4:58

2 Answers 2

2

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])

Sign up to request clarification or add additional context in comments.

Comments

1

Try this

newArr.push(...myobj);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.