-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.

user8618899
  • 13
  • 1
  • 3

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]};

EugenSunic
  • 13,162
  • 13
  • 64
  • 86
0
var array = {};

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

console.log(array)

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

Abdul Moiz
  • 447
  • 2
  • 10
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
  • 9,884
  • 4
  • 29
  • 59
-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]});
taserghar
  • 340
  • 3
  • 15
  • 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 – EugenSunic Dec 28 '19 at 23:33