parse array elements and assign to object

I have an array like ["1 apple", "2 watermelon"] and I want to convert it to object like {apple: 1, watermelon: 2}

Here is my code but I think I did something wrong:

const object = {} arr.forEach(a => {     let key = a.match(/\d+/g)     let value = a.match(/\D+/g)     Object.assign(object, {         key: value     }) }) 
Add Comment
4 Answer(s)

Use Array.map() and Object.fromEntries()

const data = ["1 apple", "2 watermelon"];  const result = Object.fromEntries(   data.map(function(item) {     let itemSplit = item.split(" ");     if( itemSplit.length > 2 ) { // ["1 apple", "2 water melon"]       return [ itemSplit.shift(), itemSplit.join(" ") ].reverse();     }     return itemSplit.reverse();   }) );  console.log(result);

Add Comment

When you use the g flag for your regex, it returns an array of matches, so you can get the first match by using [0]. For assigning one key, you don’t need Object.assign:

const arr = ["1 apple", "2 watermelon"]; const object = {};  arr.forEach(a => {     let value = a.match(/\d+/g)[0];     let key = a.match(/\D+/g)[0];     object[key] = value; }); 

This still has the issue of the leading space being in the string, so you could say value = a.match(/\D+/g)[0].substr(1);, or if you’re guaranteed to have the words separated by a space you could just split on space:

const arr = ["1 apple", "2 watermelon"]; const object = {};  arr.forEach(a => {     const [value, ...keys] = a.split(" ");     object[keys.join(" ")] = value; }); 
Answered on July 15, 2020.
Add Comment
const arr = ["1 apple", "2 watermelon"];  const object = {} arr.forEach(a => {     let key = a.match(/\d+/g)     let value = a.match(/\D+/g)     Object.assign(object, {         [value[0]]: key[0]     }) })  console.log(object)

value is an array, you need to specify an index to the element inside, also key in this case is a variable and you have to use the [] syntax when defining an object key from a variable.

This isn’t however the best solution to do this job.

Answered on July 15, 2020.
Add Comment
const arr=["1 apple", "2 watermelon"]; const object = {} arr.forEach(item => {     const [val,key]=item.split(' ');     object[key]=Number(val,10); }); console.log(object); 

Use the split function to split the string at white space. Use Array de-structuring to capture the constituent parts (i.e in first iteration item.split(' ') will return ['1','apple'] and subsequently val is assigned '1' and key 'watermelon'). Use the Number function to convert the string into an integer (the optional parameter is base, here it is 10).

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.