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.
1 Answer 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);
answered Oct 4, 2020 at 7:30
Barremian
31.2k4 gold badges37 silver badges67 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
= {}), not an array (= []).