0

I have object array, which looks like

Object {0: "tariffs", 1: "tariffs_yes", 2: "tariffs_no"}

from chrome's console

And I need to unshift this array and add {-1: 'new item'} to the beginning of array. I can't use array.unshift('newItem'); and array[-1] = 'new item...' adds item to the top of array:

Object {0: "tariffs", 1: "tariffs_yes", 2: "tariffs_no", -1: "new item..."}

How can I add to the beginning?

Filomat
  • 753
  • 1
  • 11
  • 16
  • 4
    It should be noted, according to the specs, keys from an object have no order. Why can't you use an array? – Thomas Ghesquiere Feb 19 '16 at 16:33
  • 1
    You have an object, not an array – baao Feb 19 '16 at 16:38
  • if `array.unshift()` isn't throwing error then data shown is not real representation of what you are working with. Trying to use it on that object would throw an error – charlietfl Feb 19 '16 at 16:42
  • There's no such thing as an "object array" either. It's either an object _or_ an array, and, as Thomas says, you're better off using an array `['tariffs', 'tariffs_yes', 'tarriffs_no']` for this. Using `unshift` will then work. – Andy Feb 19 '16 at 16:44
  • I got this object from `JSON.parse(response);` Should I convert all key/values to array or does JSON.parse have arguments for converting to array, not to object? – Filomat Feb 19 '16 at 16:54
  • `var arr = Object.keys(response).map(function(key) { return response[key]; });` – Thomas Ghesquiere Feb 19 '16 at 17:01
  • thx. Will use this array. – Filomat Feb 19 '16 at 17:06

2 Answers2

0

And I need to unshift this array

It's not an array, it's an object.

add {-1: 'new item'} to the beginning of array

Objects do not have beginnings and ends; they are just bags of key/value pairs.

You can add the property you want with

object[-1] = "new item";
0

You are using an object and treating it as an array. According to the definition of an Object from ECMAScript Third Edition (pdf):

4.3.3 Object An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

To be able to create a sortable collection, use an array instead.

Sha Alibhai
  • 881
  • 5
  • 7