0

I am using Angular1x and I simply want to create an array object with numeric indexes:

var unreadMessagesCookieObject = [];

unreadMessagesCookieObject[id] = {
     id: messageObj.id,
     lastNotified: moment.getTime()
};

All fine? Well no not really:

(6) [null, null, null, null, null, {…}]
0: null
1: null
2: null
3: null
4: null
5:
id: 1
lastNotified: 1601769147988

Why do I have an object with 5 null indexes. I want to write the Object to a cookie but not the 5 null values.

How can I create an array object with an arbitrary numeric index. Note that I cannot use 0 as my first index since I want to be able to search in the array object by an id.

2
  • Does this answer your question? Why does a new javascript array have 'undefined' entries? Commented Oct 4, 2020 at 0:10
  • 3
    Is this the result of a round trip through JSON? Anyway, it looks like you probably want an object (= {}), not an array (= []). Commented Oct 4, 2020 at 0:15

1 Answer 1

1

JS arrays are already list-like objects. Instead of trying to overwrite it's behavior I'd tell you to create a standard JS object instead.

let unreadMessagesCookieObject = Object.create(null);

unreadMessagesCookieObject[id] = {
   id: messageObj.id,
   lastNotified: moment.getTime()
};

Working snippet:

let unreadMessagesCookieObject = Object.create(null);

unreadMessagesCookieObject[5] = {
  id: 1,
  lastNotified: 1601769147988
};

console.log(unreadMessagesCookieObject);

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

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.