Search code examples
javascriptarraysfield-names

Create new Javascript array with field names


I have a data file that I'm reading into an array. The array created by the original data file looks like this:

var originalArray = [ {vendor: 2001, bananas: 50, apples:75, oranges: 12},
                      {vendor: 2002, bananas: 25, apples:60, oranges: 82},
                      {vendor: 2003, bananas: 36, apples:41, oranges: 73},
                      {vendor: 2004, bananas: 59, apples:62, oranges: 87}];

I select a vendor from the array using .filter (this is working fine) but then I need to change the new array (the one that contains only one vendor code) into an array that looks like this.

var desiredArray = [ {fruitName: "bananas", qty: 50},
                     {fruitName: "apples", qty: 75 },
                     {fruitName: "oranges", qty: 12} ];

Using .push I can get the quantities, but how can I get the fruit names to go from field names to values in the "fruitName" field?


Solution

  • If you've got the selected vendor object, you can do something like this to create the desiredArray.

    var desiredArray = [];
    var selectedVendor = originalArray[2]; // this is the vendor you got via .filter
    
    for(property in selectedVendor) {
        if(property !== 'vendor') {
            desiredArray.push({fruitName: property, qty: selectedVendor[property]});
        }
    }