I asked you to use console.log()
on the input object, because that will make it clear what you problem is:
// your (wrong) way
const indexe = 5;
const yourway = {
indexe: {
"input_name": 'value' // I used a string so I wouldn't have to import jQuery for this
},
};
console.log('Your original version: ', yourway);
// using a real array, this will have a lot of undefined elements
const arrayV = [];
arrayV[indexe] = {
"input_name": 'value'
}
console.log('Array version: ', arrayV);
// using an object correctly
const objectV1 = {
[indexe]: {
"input_name": 'value'
},
};
console.log('Object version: ', objectV1);
// you can add more to it like so:
objectV1[7] = {
"input_name": 'value'
};
console.log('After adding another entry: ', objectV1);
// you also don't need to create a new object with an already existing element. This will suffice:
const objectV2 = {};
objectV2[indexe] = {
"input_name": 'value'
};
console.log('2. Object version: ', objectV2);
// imortant note on the object versions: length is not defined for objects
console.log('Object version 1 length: ', objectV1.length);
console.log('Object version 2 length: ', objectV2.length);
Your problem simply was that it didn’t use the value of indexe
, but rather that as the name of a property. I have also included the array version, even though that is not an associative array (and as people in the comments have pointed out, neither are the object versions, really).
P.s. I used ES6 Syntax. It is rather widely supported, but I would still recommend going for at least ES5. (There are pre-processors for that)
If you want to make it ES5-valid, replace const
with var
and don’t use the objectV1
-version.
solved creating a multidimensional array javascript