-1

I get an error when I run this code:

var array = [];

array.push(["one"]:[1,2,3]);
array.push(["two"]:[4,5,6]);

I want my array to look like this in the end: {"one": [1,2,3], "two": [4,5,6]};

I don't know how to fix this error, I want to use push.

6 Answers6

1

An associative array in JavaScript is an object, so you can't use array.push as that's not valid there. You'd just want: array["one"] = [1,2,3]

hbh7
  • 36
  • 2
0

You should be opting for something like below. Using push, you will not achieve your desired output.

let obj = {};

const item1 = {
  ["one"]: [1, 2, 3]
}
const item2 = {
  ["two"]: [4, 5, 6]
}

obj = {
  ...obj,
  ...item1,
  ...item2
}

The reason you got the error is because you are missing object wrapper notation in your push {}

array.push({["one"]:[1,2,3]});
array.push({["two"]:[4,5,6]});

but as said, this will not give the desired output: {"one": [1,2,3], "two": [4,5,6]};

Eugen Sunic
  • 12,218
  • 8
  • 60
  • 78
0
var array = {};

array.one = [123, 123];
array.two = [123, 123];

console.log(array)

output { one: [ 123, 123 ], two: [ 123, 123 ] }

Abdul Moiz
  • 417
  • 2
  • 9
0

You must first create the object, assign values into the object, then push it into the array. Refer to this post for more information. push object into array

Dylan T
  • 139
  • 11
0

Javascript doesn't have Associative Arrays like other languages, but it have Objects, that is similar.

var object = {};

object.one = [1,2,3];

// or if the key name comes from a variable:

var key = "two";

object[key] = [4,5,6];
Elias Soares
  • 8,741
  • 4
  • 26
  • 54
-1

"one" is an object not an array. remove the parenthesis from there. See below code:

array.push({"one":[1,2,3]});
array.push({"two":[4,5,6]});
Mubashwir Alam
  • 199
  • 1
  • 14
  • I want my array to look like this in the end: {"one": [1,2,3], "two": [4,5,6]}; does not equal to your solution – Eugen Sunic Dec 28 '19 at 23:33