I want to create a multidimensional keyed array.
How do I declare the array and then push things in to it?
Is this right?
var galleryData = new Array();
$("#gallery li.gallery-image-item:not(:first)").each(function() {
galleryData.push({comment: 'comment', youTube: 'ODOIUOIhd'});
}
Thanks
That will work. An alternative syntax is
var galleryData = [];
Which is nice because yo can then do something like this:
var superGalleryData = [[],[],[]]; //creates an array of 3 arrays
Another answer suggests using an associative array but it is generally not a good idea:
http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/
If you want 'keyed' array I think you need something like
array['key'] = { comment: 'comment', youtube: 'ODD2345UI' };
Here's my test for you: http://jsfiddle.net/neuroflux/MtuLc/1/
var galleryData = [];
$("#gallery li.gallery-image-item:not(:first)").each(function() {
galleryData.push({comment: 'comment', youTube: 'ODOIUOIhd'});
});
Note that I fixed your missing bracket and changed your Array notation. I've also used jQuery just to output onto the page.
Related
I have an array that looks like this
const array: any[] = []
array.push({ 'Comments': this.comment, 'Name': this.name, 'Description' : this.description })
I pass that array back to a parent component. How can I grab the value that is in Comments?
You can use forEach loop :
const commentArray = [];
array.forEach(function(object) {
var comment = object.Comments;
commentArray.push(comment);
});
//You can store all comments in another array and use it...
console.log("This is comment array...", commentArray);
Or use map but it will work in new browsers possibly ones following ES6:
const commentArray = array.map(function(object) {
return object.Comments;
});
console.log("This is comment array... ", commentArray);
As long as TGW's answer is "correct" and works, I think you should be aware of and use for...of (and for...in) construction, it's superior over Array.forEach (faster, you can use continue and break keywords, better readability) and more often you want to iterate over your array and do things with it, than just get one property (which Array.map is perfect for in this case :) )
You may try for this:
We can also use filter here.
let commentArray:any[];
array.filter(function(object) {
var comment = object.Comments;
commentArray.push(comment);
});
//Store here and use this.
console.log("This is comment array...", commentArray);
You can use Underscore JS for short and better performance like below:
let ids: Array<number> = _.map(this.mylist, (listObj) => {
return listObj.Id;
});
I am working on a javascript homework problem and am a bit stuck:
Create a function called getFirstAnimals that returns an array of all the first animals in the object.
Example: [‘bears’,’penguins’,panther’,’flea’]
I scripted the following function:
var animals = {
mammals:['bears','lions','whales','otters'],
birds:['penguins','ducks','swans','chickens'],
cats:['panther','mountain lion','leopard','snow tiger'],
insects: ['flea','mosquito','beetle','fly','grasshopper']
}
function getFirstAnimals(array) {
var firstAnimals = [];
for (key in array) {
firstAnimals.push(array[key].slice(0,1))
}
return firstAnimals;
}
console.log(getFirstAnimals(animals));
my problem is that the output I am generating is an array of arrays made up of the first animals, [Array[1], Array[1], Array[1], Array[1]], and not the strings, [‘bears’,’penguins’,panther’,’flea’]. Any suggestions on how to get the desired output is much appreciated.
Instead of pushing array[key].slice(0,1) you need to push array[key][0], where [0] is getting you the first item in the array.
You can use
firstAnimals.push(array[key][0])
for that. It gets the first element from the array
Yet another approach
var animals = {
mammals:['bears','lions','whales','otters'],
birds:['penguins','ducks','swans','chickens'],
cats:['panther','mountain lion','leopard','snow tiger'],
insects: ['flea','mosquito','beetle','fly','grasshopper']
}
function getFirstAnimals(array) {
return Object.keys(array).map(v => array[v][0]);
}
console.log(getFirstAnimals(animals));
A oneliner: console.log(animals[Object.keys(animals)[0]]);
I am currently working on a website type project and I am new to JavaScript. So I have been having troubles with some parts of the syntax. Basically I am trying to print the 'id' and 'value' in the nested array arr.
var myArray = new Array({id:'1', value:'een', arr: new Array({id:'10', value:'een'})};
var obj = myArray[0];
document.write(obj.id);
this will print the id 1 but im not sure how to access id 10.
Also if there is an easier way to do this let me know please!
Firstly, don't use the new Array constructor. Just define an array literal [...]. So your myArray will look like:
var myArray = [{id:'1', value:'een', arr: [{id:'10', value:'een'}]}];
To get to the id of 10, you need to access myArray[0].arr[0].id;.
Proper reference would be:
obj.arr[0].id
PS: google chrome developer console is a goot playground for testing javascript object dereefrecing
You can't without iterating over the array.
If order does not matter, use an object instead:
var myObject = {
1: {id:'1', value:'een'},
10: {id:'10', value:'een'}
};
var obj = myArray[10];
document.write(obj.id);
In case the nesting in your array is intended, here's what you want:
var obj = myArray[0].arr[0];
Demo:
> var myArray = new Array({id:'1', value:'een', arr: new Array({id:'10', value:'een'})});
> myArray[0].arr[0]
{ id: '10', value: 'een' }
I would for get arrays why not create your own object ?
http://www.w3schools.com/js/js_objects.asp
I have an array, as below:
var cString = [
['1','Techdirt','www.techdirt.com'],
['2','Slashdot','slashdot.org'],
['3','Wired','wired.com']
];
to this array I want to add another in the same format:
var test = ['4','Stackoverflow','stackoverflow.com']
I've tried using:
var newArray = $.merge(cString, test);
But console.log(newArray); outputs:
[►Array,►Array,►Array,'4','Stackoverflow','stackoverflow.com']
So I'm assuming that I'm missing something obvious. Or attempting something stupid...help?
jQuery is not needed for this. Just use the Array's .push() method to add it to the main array.
var test = ['4','Stackoverflow','stackoverflow.com']
cString.push( test );
What $.merge() does is it walks through the second array you pass it and copies its items one by one into the first.
EDIT:
If you didn't want to modify the original array, you could make a copy of it first, and .push() the new Array into the copy.
var cString = [
['1','Techdirt','www.techdirt.com'],
['2','Slashdot','slashdot.org'],
['3','Wired','wired.com']
];
var test = ['4','Stackoverflow','stackoverflow.com']
var newArray = cString.slice();
newArray.push( test );
In addition to push as described by patrick, if you want to create a new list rather than changing the old, you can add arrays together with Array#concat:
var newArray= cString.concat([['4','Stackoverflow','stackoverflow.com']]);
you can use merge function like this
var newArray = $.merge($.merge([], cString), test);
This question already has answers here:
Is it possible to create an empty multidimensional array in javascript/jquery?
(8 answers)
How can I create a two dimensional array in JavaScript?
(56 answers)
Closed 9 years ago.
This wasn't the question I was going to ask but I have unexpectedly run aground with JavaScript arrays. I come from a PHP background and after looking at a few websites I am none the wiser.
I am trying to create a multi-dimensional array.
var photos = new Array;
var a = 0;
$("#photos img").each(function(i) {
photos[a]["url"] = this.src;
photos[a]["caption"] = this.alt;
photos[a]["background"] = this.css('background-color');
a++;
});
Error message: photos[a] is undefined. How do I do this? Thanks.
JavaScript does not have multidimensional arrays, but arrays of arrays, which can be used in a similar way.
You may want to try the following:
var photos = [];
var a = 0;
$("#photos img").each(function(i) {
photos[a] = [];
photos[a]["url"] = this.src;
photos[a]["caption"] = this.alt;
photos[a]["background"] = this.css('background-color');
a++;
});
Note that you could have used new Array() instead of [], but the latter is generally recommended. Also note that you were missing the parenthesis of new Array() in the first line.
UPDATE: Following from the comments below, in the above example there was no need to use arrays of arrays. An array of objects would have been more appropriate. The code is still valid because arrays are objects in this language, but the following would have been better:
photos[a] = {};
photos[a]["url"] = this.src;
photos[a]["caption"] = this.alt;
photos[a]["background"] = this.css('background-color');
You're trying to assign something to photos[a]["url"], photos[a]["caption"], etc., but photos[a] doesn't exist yet. photos is an empty Array at first, so you have to set photos[a] to something first. Since you want to use string keys ("url", "caption", etc), this something should be a plain object (the javascript equivalent to php associave arrays) (or a Hash if your code base allows it). Then you can use a literal object construct to simplify your function, and Array#push to get rid of the unnecessary a:
var photos = [];
$("#photos img").each(function(img) {
photos.push({
url: img.src,
caption: img.alt,
background: img.style.backgroundColor
});
});
Also, make sure that this is actually your img element. Some each implementations will set this to the global object in your case.
edit: ok, it looks like jQuery.each automatically sets this to the iterated element, but doesn't wrap it in jQuery-goodness, so you have to either wrap this in $() or use plain DOM (I used the latter in my example).
edit2: anyway, using this is kind of strange since the callback function passed to each receives an argument. Might as well use this argument (renamed).
var photos = [];
var imgs = document.getElementById("photos").getElementsByTagName("img");
for(var i=0;i<imgs.length;i++){
photos.push({
src:imgs[i].src,
alt:imgs[i].alt,
background:imgs[i].style.backgroundColor
});
}
That should give you something that is roughly equivalent to this in PHP (I made up pretend data):
Array(
[0] => Array(
"src" => "logo.png",
"alt" => "My Logo!",
"background" => "#ffffff"
)
)
I hope this helps!
When I read this thread I was trying to get an understanding of multidimensional associative arrays. It wasn't clear so I kept researching, this is what I came up with:
var images = new Array;
images['logo'] = { 'src': 'http://example.com/image1.png', 'caption': 'this is the logo', 'background': '#000'};
images['background'] = { 'src': 'http://example.com/image2.png', 'caption': 'this is the background', 'background': '#FFF'};
alert(images['logo']['src']); /* output: http://example.com/image1.png */
alert(images['background']['caption']); /* output: this is the background */
Hope this helps!
multi-dimensional arrays are in these structure:
var photos = new Array();
photos[0] = new Array();
use it as :
photos[0][0] = this.src;
more on JS array here.
Douglas Crockford, of JSLint, would have you create it this way ("Use the array literal notation []"):
var photos = [];
Now remember that you want to create multi-dimensional arrays, which means an array inside an array. This means you need to create the inner-arrays:
$("#photos img").each(function(i) {
photos[a] = []
//continue