ধরা যাক, আমাদের কিছু মানুষের ডেটা সহ একটি অবজেক্ট আছে এরকম -
const obj = {
"Person1_Age": 22,
"Person1_Height": 170,
"Person1_Weight": 72,
"Person2_Age": 27,
"Person2_Height": 160,
"Person2_Weight": 56
};
আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা এমন একটি অবজেক্ট নেবে। এবং আমাদের ফাংশনটি প্রতিটি অনন্য ব্যক্তির ডেটাকে তাদের নিজস্ব অবজেক্টে আলাদা করবে।
সুতরাং, উপরের অবজেক্টের জন্য আউটপুট দেখতে হবে এরকম -
const output = [
{
"name": "Person1",
"age": "22",
"height": 170,
"weight": 72
},
{
"name": "Person2",
"age": "27",
"height": 160,
"weight": 56
}
];
উদাহরণ
কোডটি হবে -
const obj = {
"Person1_Age": 22,
"Person1_Height": 170,
"Person1_Weight": 72,
"Person2_Age": 27,
"Person2_Height": 160,
"Person2_Weight": 56
};
const separateOut = (obj = {}) => {
const res = [];
Object.keys(obj).forEach(el => {
const part = el.split('_');
const person = part[0];
const info = part[1].toLowerCase();
if(!this[person]){
this[person] = {
"name": person
};
res.push(this[person]);
}
this[person][info] = obj[el];
}, {});
return res;
};
console.log(separateOut(obj));
আউটপুট
কনসোলে আউটপুট হবে -
[
{ name: 'Person1', age: 22, height: 170, weight: 72 },
{ name: 'Person2', age: 27, height: 160, weight: 56 }
]