Having transitioned from PHP to JavaScript, I am struggling with performing simple tasks involving associative arrays in JS that I could easily do in PHP. It seems like my approach might not be the best fit for this language.
Currently, I have an object that needs to be rebuilt for future purposes, with new information being added during a while cycle.
Let's consider the following initial data:
array[0] = { company: 'kfc', position: 'chicken', name: 'Andrejs', age: '20 days' }
array[1] = { company: 'kfc', position: 'chicken', name: 'Alex', age: '15 days' }
array[2] = { company: 'mcdonalds', position: 'chicken', name: 'Lena', age: '23 days' }
The desired output should look like this:
{
{kfc:
{chicken:
{name: "Alex", Age: "15 days"},
{name: "Andrejs", Age: "20 days"}
}
},
{mcdonalds:
{ chicken:
{name: "Lena", age: 23 days}
}
}
}
I have attempted the following solutions:
- Create an object:
food = {};
- To generate the object within a while loop:
food[m] = {array[i].company : {array[i].position : {name: array[i].name, age: array[i].age}}}
m++;
However, this approach failed because it resulted in separate strings within the object. 4. Attempting to use keys before the = sign:
food[array[i].company][array[i].position] = {name: array[i].name, age: array[i].age}
This led to an error due to non-existent keys during the first iteration.
I have reviewed various object tutorials but have yet to find a solution. I would greatly appreciate guidance on the correct way to create associative objects in JavaScript.