मान लीजिए, हमारे पास इस तरह की एक स्ट्रिंग है -
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' ]
}