I've got the following array which is not ideal for looping through. If I wanted to get the title of every item in the array there's no easy way to do it because the keys are unique (don't ask me how I ended up with an array that's this all-over-the-place).
productsSelectedArray = [
{cpu: {title: "Core i7 2.4GHz", price: 200}},
{memory: {title: "8GB", price: 100}},
{videoCard: {title: "nVidia 6500-GTS", price: 400}},
{display: {title: "27-inch LCD", price: 200}},
{extraBattery: {title: "", price: ""}},
{antivirus: {title: "", price: ""}},
{mouse: {title: "Logitech 232", price: 50}},
{extendedWarranty: {title: "", price: ""}}
]
I want to be able to loop through it so that it returns
"Core i7 2.4GHz"
"8GB"
"nVidia 6500-GTS"
"27-inch LCD"
""
""
"Logitech 232"
""
I'd like to convert the array above into an array like below. It's essentially removing the first key of each hash and shifting the rest of the hash over (the new "key" being the index of the array).
newProductsSelectedArray = [
{title: "Core i7 2.4GHz", price: 200},
{title: "8GB", price: 100},
{title: "nVidia 6500-GTS", price: 400},
{title: "27-inch LCD", price: 200},
{title: "", price: ""},
{title: "", price: ""},
{title: "Logitech 232", price: 50},
{title: "", price: ""}
]
This way I can loop through it and do like newProductsSelectedArray[i].title (with a loop) to display all the titles in order, and so on.
I've been trying to find a solution for this for an hour or so now, but I'm still not sure how to do it. delete just deletes the entire key along with all the values. I don't know how to remove a key and "shift" the rest of the hash over, and I don't think there would be a function like that anyway because it's kind of a nonsensical thing to normally do.
The main problem is that the key names are all different, preventing me from looping and displaying all the titles.
I could write a loop using Object.keys(productsSelectedArray[i])[0] that makes all the key names item, and then I could loop using productsSelectedArray[i].item.title but maybe there is a more elegant solution?
productsSelectedArray.map(function(o) { for(k in o) return o[k]})