I try to assign an object to an array by key but it ends up with many nulls inside besides the actual object.
First of all, I output data to an HTML data-*
attribute with PHP:
<div id="" data-my-obj=""></div>
Then I read the data object and the id
with jQuery, and I assign the the object to an empty array with the id
as the key (I get the id
somewhere else above this piece of code):
let arr = [];
let myObj = $(`#${id}`).data(`myObj`);
console.log(JSON.stringify(myObj)) // outputs {"data": "some_data"} correctly
if (arr[id] === undefined) {
arr[id] = []; // in case it was not initialized before
}
arr[id] = myObj;
But when I console log the arr
using console.log(JSON.stringify(arr))
it shows me the following:
[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, {"data": "some_data"}]
I managed to reproduce it here in a snippet but the difference here it only shows 1 null
instead of 20+:
let id = 1;
let arr = [];
let myObj = $(`#${id}`).data(`myObj`);
console.log(JSON.stringify(myObj));
if (arr[id] === undefined) {
arr[id] = [];
}
arr[id] = myObj;
console.log(JSON.stringify(arr));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div id="1" data-my-obj='{"data":"some_data"}'></div>
Comments
Post a Comment