If there are no additional levels of nesting beyond what is shown in the example, and nesting occurs only within the key "c", the code below may address your requirements. The use of type "any" was necessary for declaring the object due to constraints imposed by typescript during deletion and insertion.
let s:any = {
a: "somedata",
b: "somedata2",
c: [
{
name: "item1",
property1: "foo",
property2: "bar",
property3:{property4:"baz",property5:"foo2"},
property6:"bar2"
},
{ name: "item2",
property1: "foo",
property2: "bar",
property3:{property4:"baz",property5:"foo2"},
property6:"bar2"
},
]
};
for(let i:number=0; i<s.c.length; i++) {
let KEYS:string[] = Object.keys(s.c[i]);
let VALS:string[] = Object.values(s.c[i]);
let tempKEYS:string[] = [];
let tempVALS:string[] = [];
for(let j:number=0; j<VALS.length; j++) {
if(typeof VALS[j] === "object") {
tempKEYS.push(...Object.keys(VALS[j]));
tempVALS.push(...Object.values(VALS[j]));
delete s.c[i][KEYS[j]];
}
}
for(let j:number=0; j< tempKEYS.length;j++) {
s.c[i][tempKEYS[j]] = tempVALS[j];
}
}
console.log(s);
An alternative approach is to utilize an interface and create a new object extracting values from the existing one. This way, the usage of the "any" type can be circumvented.
interface Inner {
[property : string] : string
}
interface Outer {
a : string,
b : string,
c : Inner[]
}
let s:any = {
a: "somedata",
b: "somedata2",
c: [
{
name: "item1",
property1: "foo",
property2: "bar",
property3:{property4:"baz",property5:"foo2"},
property6:"bar2"
},
{ name: "item2",
property1: "foo",
property2: "bar",
property3:{property4:"baz",property5:"foo2"},
property6:"bar2"
},
]
};
let newS : Outer = {
a : s.a,
b : s.b,
c : []
};
for(let i:number=0; i<s.c.length; i++) {
newS.c.push({});
let KEYS:string[] = Object.keys(s.c[i]);
let VALS:string[] = Object.values(s.c[i]);
console.log(VALS.length);
for(let j:number=0; j<VALS.length; j++) {
if(typeof VALS[j] === 'string') {
newS.c[i][KEYS[j]] = VALS[j];
}
else if(typeof VALS[j] === 'object') {
let innerKEYS : string[] = Object.keys(VALS[j]);
let innerVALS : string[] = Object.values(VALS[j]);
for(let k:number=0; k<innerKEYS.length; k++) {
newS.c[i][innerKEYS[k]] = innerVALS[k];
}
}
}
}
console.log(newS);