1

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
    })
})

4 Answers 4

2

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Note this stops working for ["1 apple", "2 water melon"]
Yes @JvdV thanks for pointing it out ;) will update my answer
0

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;
});

Comments

0

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.

Comments

0
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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.