I have an array and an object and I would like to combine them by nesting the array within the object using JavaScript. I do not want to use lodash, jQuery, or any other library because my project is fairly small and I cannot add that overhead.
This is my current object and array:
var myObject = {
"key1": "value 1",
"key2": "value 2"
}
var myArray = [
{ "id": 1, "name": "name 1"},
{ "id": 2, "name": "name 2"}
]
And this is how I would like it to be structured:
var myObject = {
"key1": "value 1",
"key2": "value 2",
"myArray": [
{ "id": 1, "name": "name 1"},
{ "id": 2, "name": "name 2"}
]
}
I've tried using the JavaScript push() method, but that didn't work for me. Any guidance would be greatly appreciated. Thanks!
-
push it is for ArraysObserver– Observer2018年06月08日 18:32:40 +00:00Commented Jun 8, 2018 at 18:32
5 Answers 5
Just make an assignment to the object of your array.
myObject.myArray = myArray;
Be aware that array's are assigned by reference by default. So changing either will change both variables.
2 Comments
var a = {}; and var b = a; both a and b contain the same object. so a.foo = "bar"; console.log(b.foo);//outputs "bar" this is in contrast to scalar types (numbers, strings, boolean) which are assigned by value. If you want to be able to change myArray and myObject.myArray independently of each other, you need to make a copy of the array instead. Frequently done via myObject.myArray = myArray.slice(). Hope that helps a little bit.myObject.myArray = myArray
var myObject = {
"key1": "value 1",
"key2": "value 2"
}
var myArray = [
{ "id": 1, "name": "name 1"},
{ "id": 2, "name": "name 2"}
]
myObject.myArray = myArray
console.log(myObject)
Comments
myObject.myArray = myArray
Keep it simple.
Comments
var myObject = {
"key1": "value 1",
"key2": "value 2"
}
var myArray = [
{ "id": 1, "name": "name 1"},
{ "id": 2, "name": "name 2"}
];
myObject['myArray'] = myArray;
console.log(myObject);
Comments
Using the newest rest and spread syntax, you could also achieve it like this.
let myObject = {...myObject, myArray}