Javascript - reformatting a dictionary to an array of dictionaries

时间:2018-05-06 17:15:53

标签: javascript

I have the list of people and the frequency number in a dicitonary below, I am trying to format it as

<script>
var pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        },

    url="https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+pos.lat+","+pos.lng+"&radius=1500&type=parking&key=[YOUR KEY HERE]";
</script>

Above is the format the D3.js requires for one of the charts:

The original list:

url

How would I go about that in javascript?I tried the below code but it's giving me a wrong format:

var frequency_list = [{"text":"Jay Sekulow","size":1},{"text":"Jeff Mason","size":1},.....]   

result:

 {    'Jay Sekulow': 1,
             'Jeff Mason': 1,
             'John Bolton': 2,
             'John Dowd': 1,
             'Jonathan Oatis': 3,
             'Michael Cohen': 2,
             'Michael Dreeben': 1,
             'Mike Pence': 2,
             'Patricia Zengerle': 1,
             'Paul Manafort': 2,
             'Rod Rosenstein': 1,
             'Ronald Reagan': 1,
             'Rudy Giuliani': 2,
             'Sarah N. Lynch': 1,
             'Sergei Skripal': 2, }

3 个答案:

答案 0 :(得分:2)

var data = {
    'Jay Sekulow': 1,
    'Jeff Mason': 1,
    'John Bolton': 2,
    'John Dowd': 1,
    'Jonathan Oatis': 3,
    'Michael Cohen': 2,
    'Michael Dreeben': 1,
    'Mike Pence': 2,
    'Patricia Zengerle': 1,
    'Paul Manafort': 2,
    'Rod Rosenstein': 1,
    'Ronald Reagan': 1,
    'Rudy Giuliani': 2,
    'Sarah N. Lynch': 1,
    'Sergei Skripal': 2,
};

var finalArray = Object.keys(data).map(val => {
    return {
        "text": val,
        "size": data[val]
    }
});

console.log(finalArray);

答案 1 :(得分:1)

您应该使用新的Object.entries功能 - 或者如果您使用旧版本的javascript来支持旧浏览器,请考虑使用Object.keys

const original = {
  'Jay Sekulow': 1,
  'Jeff Mason': 1,
  'John Bolton': 2,
  'John Dowd': 1,
  'Jonathan Oatis': 3,
  'Michael Cohen': 2,
  'Michael Dreeben': 1,
  'Mike Pence': 2,
  'Patricia Zengerle': 1,
  'Paul Manafort': 2,
  'Rod Rosenstein': 1,
  'Ronald Reagan': 1,
  'Rudy Giuliani': 2,
  'Sarah N. Lynch': 1,
  'Sergei Skripal': 2
}

function formatInfo(info) {
  return Object.entries(info).map(([text, size]) => ({text, size}))
}

const formatted = formatInfo(original)

答案 2 :(得分:0)

运行以下代码段。首先解析您的输入,然后reduce将帮助您。您也可以使用lodash&#39; groupBy方法

&#13;
&#13;
const frequency_list = '[{"text":"Jay Sekulow","size":1},{"text": "Jeff Mason","size":1}]';

const a = JSON.parse(frequency_list);

const result = a.reduce((solution, item) => { 
  solution[item.text]= item.size; return solution
}, {});

console.log(result);
&#13;
&#13;
&#13;