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
 }
3
  • 2
    You just need to code: myobject.numbers = myarray If you want to use Object.assign you should code: Object.assign(myobject, { numbers: myarray }) Commented Oct 7, 2018 at 22:43
  • numbers = [1,2,3,4]; Object.assign(myobject, {numbers}); Commented Oct 7, 2018 at 22:44
  • 2
    You should learn what Object.assign does. Briefly, it copies the properties from the source object(s) to the target object. Commented Oct 7, 2018 at 22:48

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

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);

2 Comments

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.
@ S. Overflow agree - I was proposing a simpler version than getting confused over Object.Assign
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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.