How can I get John, Liza, Peter, outside of the for loop?
var siblings = ["John", "Liza", "Peter"];
for (var i=0; i < siblings.length; i++) {
names = siblings[i];
console.log(names) // correctly outputs John, Liza, Peter
}
console.log(names) // only gives Peter
Update: I was trying to reproduce the problem in a unit test case. But here is the whole thing.
So I made a request, and got an array
[ { kind: 'youtube#video',
etag: '"sZ5p5Mo8dPpfIzLYQBF8QIQJym0/XDKLx9FZygpwjYlzaTU-HAH31tw"',
id: 'b4Bj7Zb-YD4',
snippet:
{ publishedAt: '2016-10-28T07:00:01.000Z',
channelId: 'UCaHNFIob5Ixv74f5on3lvIw',
title: 'Calvin Harris - My Way (Official Video)',
description: 'Calvin Harris - My Way (Official Video)\nDownload My Way: http://smarturl.it/CHMyWay?IQid=yt\nListen to My Way: http://smarturl.it/StreamCH?IQid=yt\n\n---------\n\nFollow Calvin Harris:\nFacebook: https://www.facebook.com/calvinharris/ \nTwitter: https://twitter.com/CalvinHarris \nInstagram: https://www.instagram.com/calvinharris/ \nWebsite: http://calvinharris.com/ \n\n---------\n\nCalvin Harris - My Way (Lyrics)\n\nWhy wait \nTo say\nAt least I did it my way \nLie awake \nTwo faced \nBut in my heart I understand \nI made \nMy move \nAnd it was all about you \nNow I feel \nSo far removed \n\nYou were the one thing in my way \n\nMy way\nAway away away',
thumbnails: [Object],
channelTitle: 'CalvinHarrisVEVO',
tags: [Object],
categoryId: '10',
liveBroadcastContent: 'none',
localized: [Object] },
statistics:
{ viewCount: '8313145',
likeCount: '271119',
dislikeCount: '7364',
favoriteCount: '0' } },
{ kind: 'youtube#video',
etag: '"sZ5p5Mo8dPpfIzLYQBF8QIQJym0/c2pD6DG-ieqcYFEcGjGB31NYRKk"',
id: '0zGcUoRlhmw',
snippet:
{ publishedAt: '2016-10-24T14:00:01.000Z',
channelId: 'UCRzzwLpLiUNIs6YOPe33eMg',
title: 'The Chainsmokers - Closer ft. Halsey',
description: 'Collage EP: \nPre-order on Amazon: http://smarturl.it/CollageAmz\nUrban Outfitters White Vinyl: http://smarturl.it/CollageVinyl\n\n"Closer" ft. Halsey\niTunes: http://smarturl.it/CloseriT\nSpotify: http://smarturl.it/CloserStream\nApple Music: http://smarturl.it/CloserAM\nAmazon: http://smarturl.it/CloserAmz\n\nDirected by: Dano Cerny\n\nFollow The Chainsmokers:\nhttp://www.youtube.com/thechainsmokers\nhttp://www.twitter.com/thechainsmokers\nhttp://www.facebook.com/thechainsmokers\nhttp://www.instagram.com/thechainsmokers\nhttp://www.soundcloud.com/thechainsmokers\n\nFollow Halsey:\nTwitter: http://twitter.com/halsey\nFacebook: https://www.facebook.com/HalseyMusic\nInstagram: http://instagram.com/iamhalsey\nSpotify: http://smarturl.it/HalseySpotify\nNewsletter: http://www.iamhalsey.com/mailinglist\nPurchase Music: http://www.iamhalsey.com/badlandsbox',
thumbnails: [Object],
channelTitle: 'ChainsmokersVEVO',
tags: [Object],
categoryId: '10',
liveBroadcastContent: 'none',
localized: [Object] },
statistics:
{ viewCount: '21315027',
likeCount: '573642',
dislikeCount: '19913',
favoriteCount: '0',
commentCount: '40899' } }
]
So I put this in a variable e.g. siblings. And I loop through the entire array, to get snippet.title, snippet.publishedAt. Everything is good so far. But I want to push it into a new array, and make it available for use OUTSIDE of the loop.
My code as of now:
listVideos is the chunk I pasted before.
listVideos.forEach(function list(item) {
data = new Array();
title = item.snippet.title;
return data.push(title);
});
console.log(data); // only gives first title. I want to get all titles in an array stored inside data. And make data available globally
setting the variable var data in the beginning does not work for me, because I have other functions outside of the forEach loop. Therefore, it has to be a flexible way which I can move anywhere I want, such as some kind of function scope.
Thanks.
It only says Peter because each loop iteration you're setting 'names' to that particular name. If you want to get ALL the names, then 'names' has to be an array and you should push the names in during the loop:
names.push(siblings[i])
var names = new Array();
names.push(siblings[i]);
console.log(names);
you don't need loop:
var siblings = ["John", "Liza", "Peter"];
var str = siblings.join(',');
console.log(str); //John,Liza,Peter
Related
I used some endpoint to get simple info for all crypto coins , this list is very big
2 clear examples to illustrate the problem
// example one
var arrWithSmallLength = [ {
name: 'Bitcoin',
symbol: 'btc',
id: 'bitcoin',
image: 'bitcoin_logo_url'
},.....];
// length of arrWithSmallLength is less than 1000
console.log(arrWithSmallLength); // it prints the array normally
// example two
var arrWithBigLength = [ {
name: 'Bitcoin',
symbol: 'btc',
id: 'bitcoin',
image: 'bitcoin_logo_url'
},.....];
// length of arrWithBigLength is more than than 8000
console.log(arrWithBigLength); // it prints undefined
The arrWithBigLength rendered in VS Code in more than 78500 lines
UPDATE
find the data payload in this link : https://drive.google.com/file/d/1FIbMoLbtzRm7LqMaPZnE3EAL26sj4VOo/view
In your json file, look for the value 'Staked yAxis'. After this entry you'll find
}
]
[
{
Here you repeat your data for a second time, causing a bad json definition. Remove the doubles after this line and your data works. Everything after line 39273 shouldn't be there (except for the closing }.
I have a seed file in my project where I store dummy data to use in a mock mongoDB database. I have a "comedians" array full of comedian information and a "users" array full of user information. My relevant code looks like this:
let comedians = [
{
_id: mongoose.Types.ObjectId(),
name: "Jerry Seinfeld",
description: "Jerry Seinfeld is best known for playing a semi-fictionalized version of himself in the sitcom Seinfeld. As a standup, Seinfeld specializes in observational comedy and is revered as one of the best known and critically acclaimed comedians of his generation.",
specials: [
{
specialTitle: "I'm Telling You for the Last Time",
specialDescription: "Months after his classic TV sitcom ends, the legendary comic returns to his stand-up roots to deliver his best jokes on a sold-out international tour.",
specialRatings: [
{
userId: users[0]._id,
rating: 2
},
{
userId: users[1]._id,
rating: 5
}
],
},
],
comments: [
{
commentAuthor: "Julia Smith",
commentDate: "October 7th, 2020 at 2:30pm",
commentContent: "I Love This!",
commentLikes: [
users[0]._id,
users[1]._id,
users[2]._id
]
}
],
metrics: {
favoritesReceived: [
users[0]._id,
users[1]._id,
users[2]._id,
users[3]._id,
users[4]._id
],
views: 300
}
}
];
let users = [
{
_id: mongoose.Types.ObjectId(),
username: "userOne",
password: "userOnePassword",
favorited: [
comedians[0]._id,
comedians[1]._id,
comedians[5]._id
],
recentlyViewed: [
comedians[6]._id,
comedians[7]._id,
comedians[9]._id,
comedians[10]._id
],
}
]
The problem is that every time I try to run the test, I get an error saying that "users" is undefined. I understand that this is because I try to access it in the comedians array before it is initialized, but I can't simply move the users array to come before the comedians array, because then I'll be trying to access the comedians array before it's initialized. I'm not sure how to get around this, any suggestions?
You're still in the process of declaring the variables in your object, to prevent this; create a blank object and populate it and/or set undefined/null and add to them later.
//let fun = {
// "user":2,
// "wontwork":fun.user // this will equal undefined and throw errors but looks clever right?
//}
// Let's try the following:
let fun ={};
fun.test = "hellow world";
console.log(fun.test);
fun.tester = function() {
console.log("wow");
};
fun.tester();
let anotherway = {
"test":undefined,
"name":undefined,
"age": 20
};
console.log(anotherway.test);
anotherway.test = "1";
anotherway.test = "2";
anotherway.test = "3";
// Now equals 3
console.log(anotherway.test);
anotherway.test = () => console.warn("don't be alarmed with this warning");
console.log(anotherway.test);
anotherway.test();
let fun = {"user":2,"wontwork":fun.user};
Im completely lost. This is some test code I use to print a specific key of an object, then im printing the entire object.
console.log(docs[0].mc_ign);
console.log(docs[0]);
Now this is the output I see on the console:
The__TxT
{
id: 0,
status: 1,
testing: false,
_id: 5dbc17eb20b3a8594d569570,
timestamp: 2019-11-01T11:32:59.380Z,
mc_uuid: 'dac89e44d1024f3b810478ed62d209a1',
discord_id: '653029505457586176',
email_address: 'gut97930#eveav.com',
country: 'Germany',
birth_month: 3,
birth_year: 1943,
about_me: 'about me text',
motivation: 'motivation text',
build_images: '',
publish_about_me: true,
publish_age: false,
publish_country: true,
__v: 0
}
Where is the mc_ign key?
The object itself comes from mongoose, the missing key is added by me after the fact:
docs[i].mc_ign = mc_ign;
I tried logging the entire object before and after I add the key and assign the value. They are both the same.
What am I missing? Why can I read the value out, but cant see it?
It is mongoose document object. To achieve what you want do the following.
docs[0] = docs[0].toObject();
docs[0].mc_ign = "stuff";
console.log(docs[0])
.toObject() convert it to plain JS object.
In lunr.js, you can add a unique reference using the .ref() method but I can't find any method to add extra data/info about that particular record. Is it not possible or am I missing something really obvious.
I even tried assigning an object to ref but it saves it as a string.
EDIT
For now I am saving all the contents as a JSON string in .ref(), which works but is really ugly to use.
lunr does not store the documents that you pass it to index at all, the way it indexes means that the original document is not available to lunr at all, so there is no way of passing and storing meta data associated with the indexed object.
A better solution is to keep your records outside of lunr, and use the reference you give to lunr to pull out the record when you get the search results. That way you can store whatever arbitrary meta data you want.
A simple implementation might look like this, its overly simplistic but you get the idea...
var documents = [{
id: 1,
title: "Third rock from the sun",
album: "Are you expirienced",
rating: 8
},{
id: 2,
title: "If 6 Was 9",
album: "Axis bold as love",
rating: 7
},{
id: 3,
title: "1983...(A Merman I Should Turn to Be)",
album: "Electric Ladyland",
rating: 10
}]
var db = documents.reduce(function (acc, document) {
acc[document.id] = document
return acc
}, {})
var idx = lunr(function () {
this.ref('id')
this.field('title', { boost: 10 })
this.field('album')
})
documents.forEach(function (document) {
idx.add(document)
})
var results = idx.search("love").forEach(function (result) {
return db[result.ref]
})
I've got an issue reading a nested array from JSON(BSON from MongoHQ) using Node and Angular.
JSON snippet: http://pastie.org/9305682. Specifically look for the edges array.
Mongoose model: http://pastie.org/9305685
Basically I call the character from the DB and then attempt to log it to the console with
console.log(char); before sending it back to the angular call with res.json(char); 'char' is the returned character from the databased saved as my mongoose model.
Attempting to log the character to the console. I get everything looking normal except for the portions with the nested "effects" arrays. Anywhere they show up I receive the following:
edges:
[ { name: 'Super Hacker', notes: '', effects: [Object] },
{ name: 'Witty', notes: '', effects: [Object] },
{ name: 'Attractive', notes: '', effects: [Object] },
{ name: 'Encyclopedic Memory',
notes: 'Prereq: d8 Smarts',
effects: [Object] },
{ name: 'Daywalker', notes: '', effects: [Object] },
{ name: 'Tough', notes: '', effects: [Object] } ],
From here if I try to call it with:
From NodeJS - console.log(char[0].edges[0].effects[0].type); - Returns undefined.
From Angular View - {{cur_char.edges[0].effects[0].type}} - Displays nothing.
Thanks in advance for the help. Let me know if I can provide more in.
I think what you're asking is how to see more depth to the object in the console output. You can use util.inspect to print out more information:
console.log(util.inspect(char, { depth: 5 }));
By default util.inspect only goes to a depth of 2 which explains why you can only see the contents of the array (1) and the primitive properties of each element in the array (2).
See: http://nodejs.org/api/util.html#util_util_inspect_object_options