ধরুন, আমাদের এইরকম একটি স্ট্রিং আছে −
const str = 'dress/cotton/black, dress/leather/red, dress/fabric, houses/restaurant/small, houses/school/big, person/james';
আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা এই ধরনের একটি স্ট্রিং নেয়। ফাংশন তারপর এই মত অ্যারে একটি বস্তু প্রস্তুত করা উচিত −
const output = {
dress = ["cotton","leather","black","red","fabric"];
houses = ["restaurant","school","small","big"];
person = ["james"];
}; উদাহরণ
const str = 'dress/cotton/black, dress/leather/red, dress/fabric, houses/restaurant/small, houses/school/big, person/james';
const buildObject = (str = '') => {
const result = {};
const strArr = str.split(', ');
strArr.forEach(el => {
const values = el.split('/');
const key = values.shift();
result[key] = (result[key] || []).concat(values);
});
return result;
};
console.log(buildObject(str)); আউটপুট
এবং কনসোলে আউটপুট হবে −
{
dress: [ 'cotton', 'black', 'leather', 'red', 'fabric' ],
houses: [ 'restaurant', 'small', 'school', 'big' ],
person: [ 'james' ]
}