JavaScript - Push to Array key, value
Objects and Arrays are simple to understand data structures. However, everyday is a new learning day. Today, came across this situation where I wanted to use the push method on array to push key, value pair. The solution was very interesting and worth documenting.
// Below is the desired JSON output that we wanted to have.
"desiredArray" : [
"ourKey" : "ourValue"
];
- Create an empty object
- Use this object to insert your key and value
- Push the object into the desired array
var tempObj = {};
tempObj[ourKey] = ourValue;
desiredArray.push(obj);