How can I transform a nested object into a new object using JavaScript?
I have an object obj
where if the details property is an array, I want to use the first value of the array as the value in JavaScript.
function transformObject(obj) {
let map = {};
obj.forEach(e => {
let details = e.details;
Object.values(details).forEach(value => {
if (Array.isArray(value) && value.length > 0) {
map[value[0]] = value[0];
}
else if (typeof value === 'object') {
Object.values(value).forEach(val => { map[val] = val; });
}
})
});
return map;
}
var obj1 = [
{
details : {
"info" : ["stocks", "finance", ""],
"sales" : ["analytics"]
}
}
];
var obj2 = [
{
details : {
"city" : "SG"
}
}
];
var result1 = this.transformObject(obj1);
var result2 = this.transformObject(obj2);
Expected Output
// for obj1 (show only the first value from each array)
{
info : "stocks",
sales : "analytics"
}
// for obj2
{
city : "SG"
}