I have a dictionary which has a nested array, say
let data = {"date" : "01.01.2017", "foo":["mama", "papa", "sister", "brother"]};
Now, I need (want) to make the 'foo' array be part of the dictionary, so that 'data' looks as:
let newData = {"date" : "01.01.2017", "foo_1":"mama", "foo_2":"papa", "foo_3":"sister", "foo_4":"brother"};
I googled and found some solutions, which are close by topic, but not entirely what I need: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap
https://gist.github.com/ArtemAvramenko/d92c92ff1b74cbc55be226dcabff90cc
Flattening a Javascript dictionary, preserving the nested keys
I am a total novice in typescript and would really like some help.
I don't think there's any automatic way to do what you want, so just go through the keys and build the new object manually.
let newData = {date: data.date}
data.foo.forEach((value, index) => {
newData["foo_"+(index+1)] = value
})
Here's a more general way of doing it, in case your data is more variable. This just loops through all of the keys in the original object, and either flattens them similar to your example if they're arrays or copies them directly if they're not.
function flattenKeys (data) {
let newData = {}
Object.keys(data).forEach(key =>
if (Array.isArray(data[key])) {
data[key].forEach((value, index) => {
// build a new set of keys based on the name of the original
newData[key + "_" + (index+1)] = value
})
} else {
newData[key] = data[key]
}
}
return newData
}