user3384985 user3384985 - 17 days ago 6
Javascript Question

Getting javascript array from django json dumped dictionary

I have a

json-dump
data from
Django
view -


{"7": {"1": 0, "2": 0, "3": 0, "4": 0, "5": 0, "6": 0, "7": 0, "8": 0, "9": 0, "10": 0, "11": 1, "12": 0}}


I need an array in
javascript
from the
json
data like -

var list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]


Also I need the key "7". No
jQuery
but
javascript


Here is so far I tried -

var json_data = JSON.parse({{ vote_records }});
json_data.forEach(function(entry) {
console.log(entry);
});


What is the best way?

Answer

You could map all sorted keys for the values.

var object = { 7: { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 1, 12: 0 } },
    key = Object.keys(object)[0],
    keys = Object.keys(object[key]),
    array = keys.sort(function (a, b) { return a - b; }).map(function (k) { return object[key][k]; });

console.log('key', key);
console.log('array', array);

Comments