I can't seem to figure out as to why I am unable to append a value to my array below? Is there a special syntax to follow or something when constructing an array like in the method used below?
var arr = {
"fruits": ['apple','banana','orange']
};
arr.push({ "fruits":"testing123"}); // This line fails
alert(arr["fruits"]);
Try: arr.fruits.push("mango");
You can't push() to an object. You should either use the key-value notation:
arr.anotherFruits = "testing123"; // another key
arr.fruits = "testing123"; //to overwrite
Or make arr actually array:
var arr = [
{"fruits": ['apple','banana','orange']}
]
arr.push({ "fruits":"testing123"})
alert(arr["fruits"])
In this case you'd get
var arr = [
{"fruits": ['apple','banana','orange']},
{"fruits":"testing123"}
]
Or in case you did want to get an object like this
var arr = {
"fruits": ['apple','banana','orange','testing123']
}
you should've used arr.fruits.push('testing123');
Your array defintion is all wrong. Assuming you want arr to be an object that has an array under fruits and then push another value inside fruits, use the following:
var arr = {
fruits: ['apple', 'banana', 'orange']
};
arr.fruits.push("testing123");
console.log(arr["fruits"]);
Change your initial arr declaration to this...
var arr = [{
"fruits": ['apple','banana','orange']
}];
Then you can push more objects onto it. E.g.
arr.push({"fruits": ['mango', 'pear', 'tomato']});
Or, if you wish to push fruits to the existing array INSIDE your object, then simply use your existing arr declaration and use it like this...
arr.fruits.push('tomato');
arr.fruits.push('pear');
arr.fruits.push('tomato');
I'd argue that you don't really require this to be an object at all here.
All you need is this...
var fruits = [];
fruits.push('banana');
fruits.push('apple');
It's simply an array of fruits. If you need more complex structure, then use an array of objects, instead of strings.
Array has push() method, but Object does not. Here you create an Object, but not an Array. So it failed.
Related
Im trying to push my array of objects into variable, but all i I recieve is Array in Array, or single object.
myObject = {
id: id,
items: [],
boolean: true,
}
myArray = [{1}, {2}, {3}]
I tried myObject.items.push(myArray[0]) but this returns only first object. Without 0 its double array.
What i want is
myObject = {
id: id,
items: [{1}, {2}, {3}],
boolean: true,
}
What you're going to want to do here is set the entire array as the new value like this:
myObject.items = myArray
If you want to take the immutable approach then you can copy it like this:
myObject.items = [...myArray]
Edit:
If you want to add items (and not just complete overwrite) to myObject.items then you should do this:
myObject.items = [...myObject.items, ...myArray]
That will add your new array items to the end of the current items array, you could also do this to add them to the start:
myObject.items = [...myArray, ...myObject.items]
you can use this
myObject.items.push(...myArray)
As Andreas commented another solution is to use concat. Concat is similar to push. But it doesn't actually change the array it returns a new one.
const x = []
console.log(x.concat(3)) // prints [3]
console.log(x) // prints []
This behavior is often desired as it prevents "side effects" from occurring
It also doesn't just append items to an array, it only does this if the item is not an array. If it is an array it will merge the two arrays
const x = [1,2,3]
console.log(x.concat([4,5,6]) // prints [1,2,3,4,5,6]
so a solution here is
myObject.items = myObject.items.concat(myArray)
//object
myObject={
id:1,
items:[],
boolean: true
}
//concat
myArray = [ 1,2,3];
myObject.items += myArray;
console.log(myObject.items);
I need to add ann array to an existing array.
If i have an array
var array = ["foo", "baah"];
then, what i need to do is to add an array into the existing one. So it ends up looking like
var array = ["foo", "baah", ["newfoo", "newbaah"]];
i need to do it client site, so using javascript or JQuery. Anyone who can help me? If i can't add a array to a array, is i then possible to add an object
Something like
var array = ["foo", "baah", /*myObject containing 2 item*/];
just ask for more info if needed.
Just .push will do it
var array1 = ["foo", "baah"];
var array2 = ["newfoo", "newbaah"];
array1.push(array2)
console.log(array1)
const arrOne = [1,2,3];
const arrTwo = [4,5];
arrOne[arrOne.length] = arrTwo;
console.log(arrOne);
You don't need to use .push(), you can use index notation.
Just use push:
var array1 = ["foo", "baah"];
var array2 = ["newfoo", "newbaah"];
array1.push(array2);
console.log(array1);
You can do it via ... spread operator.
var array1 = ["foo", "baah"];
var array2 = ["newfoo", "newbaah"];
var array3 = [...array1, array2];
console.log(array3);
.push will mutate your first array but this one doesn't.
Push
You can use push to add one array to another
var a = [1,2]
var b =[3,4]
a.push(b) //[1,2,[3,4]]
unshift
This is similar to push but adds the array to the first
a.push(b) //[[3,4],1,2]
concat
a.concat(b)//[1,2,3,4]
concat returns a new array rather than push and unshift which adds in the existing array
I have an Object array that looks like the following:
var array = [
{'id':1,'description':test},
{'id':2,'description':test},
{'id':3,'description':test}
]
And I want to convert it to look like this:
var newArray = [
1, 2, 3
]
So it's basically taking the object array, extracting the id's out of the objects, and creating a new array that contains the id's that were extracted. Is there a way to do this in one line? Even better if a new array doesn't have to get created and array is just updated.
var test ="sai";
var array = [
{'id':1,'description':test},
{'id':2,'description':test},
{'id':3,'description':test}
]
console.log(array.map(function(obj){return obj.id}))
iterate the array using foreach and populate newArray
var newArray = [];
array.forEach(funtion(element){
newArray.push(element.id);
});
console.log( newArray );
array.map(function (item) {
return item["id"];
}
If you'd like to have anew instance of the mapped array:
var newarray = [];
array.forEach(function (item) {
newarray.push(item["id"]);
}
array.map(function(element) {return element.id})
OP Requirement: better if array is just updated
array = array.map(function(element) {return element.id})
I have to write a function that will create an array filled with the indicated number of objects that represent three "types" of these objects.
WITHOUT using for or while loop and not doing that manually?
I don't know how can I add these objects into the array.
I'm choosing the type of object by random, but how can I add them to the array?
these are the objects:
var bestaccount=function(){
var amount=0;
this.pay=function(howmuch){amount+=howmuch;};
this.widthdraw=function(howmuch){amount-=howmuch;};
this.saldo=function(){return amount;};
};
var toGive= function(){
var amount=0;
this.pay=function(howmuch){amount+=howmuch;};
this.saldo=function(){return amount;};
};
var toWithdraw=function(){
var amount=0;
this.withdraw=function(howmuch){amount-=howmuch;};
this.saldo=function(){return amount;};
};
For example there are 3 toWithdraw objects, 1 bestAccount and 1 toGive. I want them all in one array.
EDIT:
Sorry, I was using completely wrong functions.
If anyone needs it, I'm doing it with apply().
Here's the code:
function fillArrayWithNumbers(n) {
arr = Array.apply(null, Array(n));
tabl= arr.map(function (x, i) { return new objects[Math.floor(Math.random()*objects.length)](); });
return tabl;
}
Sorry, but no stress guys. Everyone started somehow.
Now that you have answered your own question, I see that I have misinterpreted it. Anyway, here is how to add objects to an array:
You can add new elements to an array with push like this:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
Now, instead of an array with strings, you want an array with objects. So you can first create the object like this:
var myObject = {numberOfGive: 1, numberOfWithdraw: 3, numberOfBestAccount: 1};
And then push it to your array:
var myArray = [];
myArray.push(myObject);
Source
here's my solution:
var objects =[bestaccount,toGive,toWithdraw];
function fillArrayWithNumbers(n) {
arr = Array.apply(null, Array(n));
tabl= arr.map(function (x, i) { return new objects[Math.floor(Math.random()*objects.length)](); });
return tabl;
}
Thanks for response.
I have an array that loads an array with properties at a certain index:
var hotspotLocationsTextAndAudio [];
var myArr = [
[{x:10, y:40, filename:"test", text:"test"}],
[{x:50, y:60, filename:"test2", text:"test2"}]
];
hotspotLocationsTextAndAudio[window.IDNum] = myArr;
To access a property at a certain index of hotspotLocationsTextAndAudio (my case being what window.IDNum equals) at an index of the array inside that (0) and a certain property, I thought I just needed to do the following:
alert(hotspotLocationsTextAndAudio[window.IDNum][0].x);
That returns undefined.
Assuming the code you're actually using is this:
var hotspotLocationsTextAndAudio [];
var myArr = [
[{x:10, y:40, filename:"test", text:"test"}],
[{x:50, y:60, filename:"test2", text:"test2"]}
];
hotspotLocationsTextAndAudio[window.IDNum] = myArr;
The alert code you'll need is:
alert(hotspotLocationsTextAndAudio[window.IDNum][0][0].x);
The reason being that you wrapped your objects in [], putting them in an array.
Or, in order to have your original alert working, you'll need to change myArr to this:
var myArr = [
{x:10, y:40, filename:"test", text:"test"},
{x:50, y:60, filename:"test2", text:"test2"}
];
This works for me: http://jsfiddle.net/Ku2tQ/
var hotspotLocationsTextAndAudio = [];
var myArr = [
[{x:10, y:40, filename:"test", text:"test"}],
[{x:50, y:60, filename:"test2", text:"test2"}]
];
alert(myArr[1][0].x);
First of all hotspotLocationsTextAndAudio is an empty array, and you never push/merge myArr to it. So trying to access a nested value of an empty array, will fail.
arr, is also never defined.
If possible, keep it simple and try avoiding nested array with too much deep.