Skip to content Skip to sidebar Skip to footer

Convert Array Values To Object Keys

I do a get which returns me a json object like so: 'data': [ [ '2016 Pass/Fail Rates by Test Centre', '', '', '', '', '', '', '', '', ''

Solution 1:

You can iterate over your array while adding your index and value into an object...

You can find an example on how you can iterate objects and arrays here and an example here

Generally, to add an item to object

vararray = [{"Location":"Sometown"}, {"Location2":"Sometown2"},    {"Location3":"Sometown3"}],
object = {};
array.forEach(function(element, index) {
    object[index] = element;
});
console.log(object);

Solution 2:

You could take the second array as keys for the wanted objects and iterate only the part after the keys. Then iterate the keys and build a new object for the values of the array. Return the object for mapping for a new array.

var data = { data: [["2016 Pass/Fail Rates by Test Centre", "", "", "", "", "", "", "", "", ""], ["Location", "Passes", "Passes%", "No ID", "No ID%", "Fails", "Fails%", "Fail Dangerous", "Fail Dangerous%", "Total"], ["Sometown", "8,725", "53.40%", "140", "0.90%", "7,417", "45.40%", "48", "0.30%", "16,330"], ["Some Other Town", "12,778", "44.80%", "193", "0.70%", "15,422", "54.10%", "103", "0.40%", "28,496"]] },
    keys = data.data[1],
    result = data.data.slice(2).map(function (a) {
        var temp = {};
        keys.forEach(function (k, i) {
            temp[k] = a[i];
        })
        return temp;
    });
    
console.log(result);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Post a Comment for "Convert Array Values To Object Keys"