मान लीजिए, हमारे पास एक स्ट्रिंग है जैसे -
const str = 'dress/cotton/black, dress/leather/red, dress/fabric, houses/restaurant/small, houses/school/big, person/james';
हमें एक JavaScript फ़ंक्शन लिखना है जो ऐसी एक स्ट्रिंग लेता है। फ़ंक्शन को फिर सरणियों का एक ऑब्जेक्ट तैयार करना चाहिए जैसे -
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' ] }