0

I need to add key:value into an object.

var a = {}
a['first'] = [a,bunch,of,stuff]
a['eight'] = [another,bunch,of,stuff]
a['two'] = [more,stuff]

but now variable 'a' contains

{eight: [a,bunch,of,stuff],first: [another,bunch,of,stuff],two: [more,stuff]}

while what I wanted was

{first: [another,bunch,of,stuff], eight: [a,bunch,of,stuff],two:[more,stuff]}

I'm guessing the order is based on the alphabetical order of the keys. This is a problem, because I want to display the data into hbs using {#each model as |key value|} in the same order as I wanted it.

Jino Shaji
  • 1,097
  • 14
  • 27
Flyn Sequeira
  • 718
  • 2
  • 9
  • 25
  • Possible duplicate of [Sort JavaScript object by key](https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key) – genesst Sep 19 '17 at 04:45
  • have a look at this as well - https://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value – genesst Sep 19 '17 at 04:45
  • Not really. I don't want it sorted. I want it in an arbitrary order which I prefer it to be in. – Flyn Sequeira Sep 19 '17 at 05:21

2 Answers2

1

in most languages lists have order where objects and sets do not. objects are key value and have no order.

in js arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays

this basically means you can place data anywhere in array, and it will be in order in the array

var idx = [];
idx[0] = 'hello';
idx[999] = 'world';

so what i believe you're looking for is

var listOfThings = [];
listOfThings.push({ 'first': [ 'things' ] })
listOfThings.push({ 'eight': [ 'stuff' ] })
listOfThings.push({ 'two': [ 'more'. 'things' ] })

then you can loop over accessing the key and value for each object.

denov
  • 11,180
  • 2
  • 27
  • 43
0

Example you have an object, which is already have 2 key pairs, a1 & b2. Then you would like to add k3, you can use this method :

let objData = [{"a1":10,"b2":20},{"b2":11,"a1":23}]
Object.keys(objData).map(
function (object) {
    // add k3
    objData[object]["k3"] = "foo"
})

Then if you want to sort the keys alphabetically, use this method :

function orderKeyAlfAsc(obj) {
    let data = []
    for (var i in obj)
        data.push(Object.keys(obj[i]).sort().reduce((r, k) => (r[k] = obj[i][k], r), {}))
    return data
}

let orderedData = orderKeyAlfAsc(objData)
mrJ0ul3
  • 126
  • 7