0

I am new to javascript. I have an array of data in the format:

Toronto, Ontario: 95 
Markham, Ontario: 71

I want to convert it to an array of object:

enter image description here Like this, to be consistent with other functions.

I tried:

reportData.fbcity = Object.keys(reportData.city).map((city) => {
    return {
        city: city,
        value: reportData.city[city]
    };
});

What I get is: {city: "Markham, Ontario": "value": 71}

kevin
  • 309
  • 2
  • 12

3 Answers3

1

Based on your updated question, I take it that you have this:

const start = ["Toronto, Ontario: 95", "Markham, Ontario: 71"];

and you want this:

result = [
    {"Toronto, Ontario": 95},
    {"Markham, Ontario": 71}
];

To do that, you need to split the number at the end of the string off, and then build objects with the two parts of the string. If you know there's only ever one :, then:

const result = start.map(str => {
    const [city, number] = str.split(":");
    return {
        [city]: +number
    };
});

Live Example:

const start = ["Toronto, Ontario: 95", "Markham, Ontario: 71"];
const result = start.map(str => {
    const [city, number] = str.split(":");
    return {
        [city]: +number
    };
});
console.log(result);

That uses destructuring to capture the two parts from split, then a computed property name to create a property with the city name, and + to coerce the number to number from string. (That's just one of your number-to-string options, see this answer for more options.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    I was hoping to know some interesting reason to use :) – Code Maniac May 29 '19 at 16:58
  • 1
    @CodeManiac - Nope, there's really no justification and I'm going to remove it. :-) [The spec](https://tc39.github.io/ecma262/#sec-tonumber-applied-to-the-string-type) is quite clear about the whitespace being handled. – T.J. Crowder May 29 '19 at 16:59
0
reportData.fbcity = Object.keys(reportData.city).map((city) => {
    return {
        [city]: reportData.city[city]
    };
})
Amit Chauhan
  • 6,151
  • 2
  • 24
  • 37
0

You can use map and split

  • split with : and than build a object
  • + is used to convert string to number

let data = ["Toronto, Ontario: 95", "Markham, Ontario: 71"];


let op = data.map(val=>{
  let [key,value] = val.split(':')
  return {[key]: +value}
})

console.log(op)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60