kevin
kevin

Reputation: 309

Java script key value pair to object

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}

Upvotes: 0

Views: 160

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074038

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

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

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)

Upvotes: 0

Amit Chauhan
Amit Chauhan

Reputation: 6869

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

Upvotes: 0

Related Questions