Search This Blog

2024/03/28

Javascript:Convert nexted Object to an array

Sample Input:

var sampleInput={
name: {
firstName: "sangram",
midddleName: "shivaji",
lastName: "Desai",
},
address: {
street: "Naradawe Road",
line1: "near railway station",
line2: "behind annapurna hotel",
city: "kankavali",
pin: "416602",
},
};

Sample Output:
var sampleOutput= [
["name",[
["firstName","sangram"],
["midddleName","shivaji"],
["lastName","Desai"]
]
],
["address",[
["street","Naradawe Road"],
["line1","near railway station"],
["line2","behind annapurna hotel"],
["city","kankavali"],
["pin","416602"]
]
]
]

Solution:
const person = {
name: {
firstName: "sangram",
midddleName: "shivaji",
lastName: "Desai",
},
address: {
street: "Naradawe Road",
line1: "near railway station",
line2: "behind annapurna hotel",
city: "kankavali",
pin: "416602",
},
};
function convertObjectTwoArray(person) {
let resultArray = [];
for (let key in person) {
if ((typeof person[key]).toString() === "object") {
resultArray.push([key, convertObjectTwoArray(person[key])]);
} else {
resultArray.push([key, person[key]]);
}
}
return resultArray;
}
//find result & print
let resultArray = convertObjectTwoArray(person);
console.log( JSON.stringify(resultArray));
Output:

[
["name",[
["firstName","sangram"],
["midddleName","shivaji"],
["lastName","Desai"]
]
],
["address",[
["street","Naradawe Road"],
["line1","near railway station"],
["line2","behind annapurna hotel"],
["city","kankavali"],
["pin","416602"]
]
]
]

No comments:

Post a Comment