-1

I have an object that I need to transform into an array. Here is the code I have already:

    for (var key in categoryData[p]) { // categorydata is an object, the "p" is because this is taking place in a loop (array of objects)
      if (categoryData[p].hasOwnProperty(key)) {
        var objToArray = $.map(categoryData[p], function(value, key) {
          return [value];
        });
      }
    }

Right now, this is returning:

0 : value
1 : value
2 : value

I want it to return:

Key : Value
Key : Value
Key : Value

But I haven't found a way to do this with my data. Any direction would be greatly appreciated!

Edit: Adding more information:

I want to sort from the highest to lowest value. For clarification, I want the data to look like this:

(key)  (object)
"ABC" : 8
"DEF" : 7
"GHI" : 5

I am putting it into an array to begin with because I can't sort the values when they're in an object (as far as I know).

My data is fairly complex, in a CSV file, but the idea of it is:

ABC, DEF, GHI
8  , 7  , 5
  • please add the data as well. – Nina Scholz Feb 06 '17 at 22:23
  • `return [value];` and $.map create arrays... arrays are 0 indexed. What you want is something that is indexed by keys, so, clearly arrays aren't what you want.. – Kevin B Feb 06 '17 at 22:26
  • Why do you loop to assign the same value again and again to `objToArray`? That makes no sense. – trincot Feb 06 '17 at 22:28
  • @KevinB, could you point me in a direction of something that could be indexed by keys? Basically, I put this data into an array to begin with because I needed to sort the values. – Jessica L. Feb 06 '17 at 22:30
  • An object, for example. `{foo: 'bar'}`. In this case, `foo` is the key, and `'bar'` is the value. – Kevin B Feb 06 '17 at 22:30
  • @trincot I'm a beginner, I'm trying my best. To clarify, I have an array of objects, and I'm turning the objects into an array so I can sort the values (from highest to lowest) – Jessica L. Feb 06 '17 at 22:31
  • 1
    object keys cannot be sorted by their values, therefore, your original data structure (array of objects) is likely the structure you need to use. – Kevin B Feb 06 '17 at 22:32
  • Even if you sort the array, it will have no use to turn it back into an object, as you will get the same thing you started with. – trincot Feb 06 '17 at 22:33
  • you need to sort the objects in your array by the value of the object keys, right? – Kevin B Feb 06 '17 at 22:34
  • Edit your question to provide the data you have (don't dump this in comments). – trincot Feb 06 '17 at 22:34
  • @trincot I apologize, I should have added more information to my original post. I will update in a moment. I am doing this as part of a larger d3.js project, and I need to sort the values from highest to lowest in each object. After I sort the values in the array, I want to put them back into an object to use. – Jessica L. Feb 06 '17 at 22:37
  • Did you try removing square brackets? - `return value;` – Archi Feb 06 '17 at 22:39
  • We need the data. – Darkrum Feb 06 '17 at 22:41
  • As Kevin has already told you: don't try to get properties sorted in an object. Instead use -- and keep using -- a 2D array for that, in the format: `[['abc', 34], ['x', 12], ['fsdfds', 6]]`. Arrays are to be used if order is important. [see here](http://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value), and [here](http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – trincot Feb 06 '17 at 22:54
  • What is in `categoryData[p]`? Its really unclear from your example what you are trying to do. Try simplifying the question and give the exact input and the output you are trying to achieve. Its not clear what the input in this case is. – GantTheWanderer Feb 06 '17 at 23:01

3 Answers3

2

Associative arrays aren't a thing in javascript. You can either have arrays denoted by [] with 0 based numeric indices, or objects denoted by {} that can store key-value pairs. The latter construct can be used as replacement to associative arrays (ie add arbitrary keys and values to it), but they cannot be treated like arrays.

What you want in this case is what you already have - a key/value store, except it's called an object.

edit

If you just want to sort the data regardless of datatypes

You can split your object into multiple objects with a single key-value pair, then create an array from these objects and sort them any way you like using Array.sort(). Here's a quick example of splitting your provided data into objects:

var originalData = {
        "ABC" : 8,
        "DEF" : 7,
        "GHI" : 5,
    },
    sortableArray = [];

for (key in originalData) {
    sortableArray.push({
        "key"   : key,
        "value" : originalData[key]
    });
}

This creates a new object and appends it to our sortable [] array. To sort it according to its original value, you need to supply a comparator function that accesses the value property of the objects.

sortableArray.sort(function(a,b) {
    return a.value - b.value;
});

This should return an array of objects ordered by the value property of each object in ascending order. Simply switch a and b around to get a descending order sort.

Hope this helps!

ppajer
  • 2,612
  • 1
  • 11
  • 20
  • Thank you. I appreciate your time and explanation, that makes sense to me. Is there a way to sort data from highest to lowest in an object, or am I stuck manually sorting the data? (Sorry if this is too big of a question to answer here) – Jessica L. Feb 06 '17 at 22:44
  • You can't really sort keys in objects as they are unordered by definition, but if you turn the value itself into an object and move the key into it, you can Array.sort() it. I'll update my answer with a better explanation – ppajer Feb 07 '17 at 00:26
  • @JessicaL. Updated. – ppajer Feb 07 '17 at 00:41
1

The best approach to sort your data is to map your object into an array to look like this:

[
    {
        "key": someKey
        "value": someValue
    },
    {
        "key": someOtherKey
        "value": someOtherValue
    },
    //...
]

using this code:

var objToArray = $.map(categoryData[p], function(value, key) {
      return {"key": key, "value": value};
});

And then sort it using this code:

objToArray.sort(function(a, b) {
    // if the values are numbers (otherwise you have to change this to addapt to your dataType)
    return b.value - a.value; // to sort from highest to lowest or a.value - b.value to sort from lowest to highest
});

And then you can use it like:

objToArray[0].key; // to get the key of the first item

objToArray[3].value; // to get the value of the 4-th item

// ...

You can loop through them as well (for(var i = 0; i < objToArray.length; i++)...).

ibrahim mahrir
  • 28,583
  • 5
  • 34
  • 61
0

In ES6, Object.entries(a).sort((a, b) => a[1] < b[1] ) This will give you something like this

[ ["ABC", 8] ["DEF", 7] ["GHI", 5] ]

the .entries step gives you the list of pairs and the .sort step sorts them by their second value

mrBorna
  • 1,638
  • 16
  • 16