Search This Blog

2024/03/28

Javascript:Convert Array to Object

Sample Input:

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"]
]
]
]

Sample Output:

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",
},
};





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 convertArrayToObject(person) {
let resultObject = {};
for (let element of person) {
if (Array.isArray(element[1])) {
resultObject[element[0]] = convertArrayToObject(element[1]);
} else {
resultObject[element[0]] = element[1]
}
}
return resultObject;
}

//find result & print
let resultObject = convertArrayToObject(person);
console.log(resultObject);


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