0

I have an array with values that look like so

myarray= [1,2,3,4,5,6]

I have an object with different objects already in it

myobject ={
  key1: value1,
  key2: value2,
  key3: value3
}

I want to add my array into this object and give it a key text as 'numbers' to look like this

myobject ={
  key1: value1,
  key2: value2,
  key3: value3
  numbers: [1,2,3,4,5,6]
}

I've tried

Object.assign(myobject, myarray);

but the results come out like this

{
  0:1,
  1:2,
  2:3,
  3:4,
  4:5,
  key1: value1,
  key2: value2,
  key3: value3
 }
dee-see
  • 23,668
  • 5
  • 58
  • 91
jumpman8947
  • 571
  • 1
  • 11
  • 34
  • 2
    You just need to code: `myobject.numbers = myarray` If you want to use `Object.assign` you should code: `Object.assign(myobject, { numbers: myarray })` – Ram Oct 07 '18 at 22:43
  • `numbers = [1,2,3,4]; Object.assign(myobject, {numbers});` – Ele Oct 07 '18 at 22:44
  • 2
    You should learn what [*Object.assign*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) does. Briefly, it copies the properties from the source object(s) to the target object. – RobG Oct 07 '18 at 22:48

3 Answers3

3

You can just assign it like you would assign any other value: myobject.numbers = myarray.

nikos fotiadis
  • 1,040
  • 2
  • 8
  • 16
1

Why you don't add it like this: myobject["numbers"] = myarray;

let myarray= [1,2,3,4,5,6];

let myobject ={
  key1: 1,
  key2: 2,
  key3: 3
}

console.log(myarray);
console.log(myobject);

myobject["numbers"] = myarray;
console.log(myobject);
L J
  • 5,249
  • 3
  • 19
  • 29
  • Lijo - I guess it is 6 one way, a half a dozen another, but declaring object properties as an associative array (IMHO) is not really good object oriented programming. JavaScript is the wild wild west with styles, but... anyhow. Just my opinion. – Mark C. Oct 07 '18 at 23:15
  • @ S. Overflow agree - I was proposing a simpler version than getting confused over Object.Assign – L J Oct 08 '18 at 06:28
0

Pretty sure this one is nearly trivial, yes? You want to add another property to your object so just declare it:

var numbers = [1,2,3,4,5]
var myobject ={
   key1: 'test',
  key2: 'test2',
  key3: 'test3'
}

myobject.numbers = numbers;
Mark C.
  • 378
  • 1
  • 12