json find object by name and grab its value (api) [closed] - node.js

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
i am grabbing the steam data and saving it to variable called body
now what i want to do is find total_kills its not necessary that this object is always at body.playerstats.stats[0].value so is there any way to find the body by total_kills and get its value
the complete api reply is given below with beautified form
https://codebeautify.org/jsonviewer/cb2b563d

It seems like body.playerstats.stats is an Array that contains objects. What you could do is go through that array and store all the objects that have name: 'total_kills', something like this could work:
const totalKillsArr = body.playerstats.stats.filter((stat) => {
return stat.name === 'total_kills';
});
Once you have the new array of totalKills you can use reduce to get the sum of all total kills:
const sumTotalKills = totalKills.reduce((sum, el) => {
sum += el.value;
return sum;
}, 0);
If there is only one object in the stats array that has the name of total_kills then just use a simple find function on the main array like this:
const totalKills = body.playerstats.stats.find(stat => {
return stat.name === 'total_kills';
});
This will find you the first object with name property of total_kills. If there is no such object it will return undefined.

Related

How to get the id from the given lines of code?

{
acknowledged: true,
insertedId: new ObjectId("612d9d08db9c20f031033478")
}
This was the JSON format I got while I added a file and some other things to MongoDB and I want to get this id separately to save the file to another folder.
Can anyone please explain this?
I believe this question was answered by Vikas in this thread How to get value from specific key in NodeJS JSON [duplicate]
Edited The Answer. Now Its working for above object in question
You can use following function to access the keys of JSON. I have
returned 'mm' key specifically.
function jsonParser(stringValue) {
var string = JSON.stringify(stringValue);
var objectValue = JSON.parse(string);
return objectValue['mm'];
}
if this is a JSON String, at first of all you have to parse it to object liertal, then you can access the specified property you mentioned, so you can do like the following:
function parseJsonString(jsonString) {
// first parse it to object
var obj = JSON.parse(jsonString);
// now access your object property/key
var id = obj.insertedId;
}
If your doing it on mongodb shell or Robo3T then, the line of code would be:
db.collection_name.find({},{insertedId:1})
This is related to projection. 1 represents you want to display it as your output.
In your case as you want only the value of your object id to get displayed, you have to use .valueOf() ; that is ObjectId().valueOf().
-> insertedId: new ObjectId("612d9d08db9c20f031033478")
-> ObjectId("612d9d08db9c20f031033478").valueOf()
->
-> 612d9d08db9c20f031033478
Your can refer this : https://docs.mongodb.com/manual/reference/method/ObjectId.valueOf/ site for your reference.
So you can use this .valueOf() in your code and get the id saved in the document

Azure search schema migrations [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
What's the best way to migrate an Azure search schema in a release pipeline?
In the SQL world, I'd use something like DbUp. Is there anything similar for Azure search?
Or is there a different approach when the schema needs to change?
It depends on whether you are pushing content via the SDK or if you are pulling content from a supported content source using one of the pre-built indexers. Using the SDK you can add new properties to your model as explained in this post: Update Azure search document schema
Note: Changes in your data model may require either an update or a rebuild of the index. For example, adding new properties only requires and update. But, if you change a setting like searchable, filterable or sortable you will need a rebuild. For details, see How to rebuild an index in Azure Cognitive Search
COMPATIBILITY PROBING VIA PUSH
My preferred solution is to use push indexing for everything. To test if the data model in the index is compatible, I create a sample item and submit to the index. If the model used in the index is incompatible, and error is thrown by the Azure Search SDK. I then delete the index and create it from scratch using my new model.
Here is a simplified method to test if any item is compatible with a named index:
public async Task<bool> TestItemAsync<T>(T item, string indexName)
{
var isCompatible = false;
var indexClient = _searchServiceClient.Indexes.GetClient(indexName);
var indexActions = new List<IndexAction<T>> { IndexAction.MergeOrUpload((item)) };
var batch = IndexBatch.New(indexActions);
try
{
var unused = await indexClient.Documents.IndexAsync(batch);
isCompatible = true;
}
catch
{
// ignored
}
return isCompatible;
}
And here is an example of how you might use it to probe your index for compatibility.
var item = new Product();
item.ID = 123;
item.Title = "Sample";
item.MyNewProperty = "Some value"
// ...
var isCompatible = await TestItemAsync(item, indexName);
if (isCompatible)
{
await DeleteItemAsync(item, indexName);
}
else
{
await DeleteIndexAsync<T>(indexName);
await CreateIndexAsync<T>(indexName);
}
To actually verify the compatiblity, make sure you populate your item with some values. In this example I hard-coded some values for the sake of the example. In actual use I use a Mock framework that populates every property of my item with some random sample value, but I did not want to give the impression that a third-party component is required for this use-case.

In Microsoft Bot Framework session.conversationData.array of regexes changes to array of Object type after executing once

I am working with the below piece of code in Microsoft Bot Framework to access the list of regexes for global commands. This code is a part of botbuilder module:
if (typeof session.conversationData.globalCommands === "undefined") {
// An array which contains the list of all global commands
session.conversationData.globalCommands = [];
// Accessing the list of global commands
globalActions = session.library.actions.actions;
lenGlobalActions = Object.keys(globalActions).length;
// Assigning values to the above list
for (var i=0; i<lenGlobalActions; i++){
session.conversationData.globalCommands.push(globalActions[Object.keys(globalActions)[i]].options.matches);
}
}
// Checking if the incoming message from the user is a global command
var isGlobalCommand = session.conversationData.globalCommands.some(regex => regex.test(session.message.text));
The issue here is, the code runs fine for the first time and the values assigned to the variable session.conversationData.globalCommands are in the form given below:
However, after the first execution, the array converts to the below without any changes made in the code anywhere else:
Due to this, the line:
var isGlobalCommand = session.conversationData.globalCommands.some(regex => regex.test(session.message.text));
throws an exception "regex.test is not a function".
I am unable to understand why this should be happening and how do I solve this as I need this list separately for some processing.
I believe you cannot store complex types in the bot store (conversationData, etc). The object needs to be serializable to JSON and I don't believe a RegExp it is.
The workaround would be to store the regex as an string and then recreate the regex object using the constructor and the stored string expression.
Check the core-State sample to know more about the store capabilities.

Best way to Spell Check a web page [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
When adding text to a webpage best practice would be to use localization resources, or at least copy/paste text out of a program like Word (or any other grammar/spell checker). That being said there are "always" a couple words here and there where a developer just "updates it."
My question, how do other people check for typos on their webpages? I have a solution (Which I will post as a possible answer), but looking for other ideas.
You can add a function in your javascript library to grab all text and put it in a textbox, which on a browser like chrome will then trigger the native spellchecker.
function SpellCheck()
{
var ta=document.createElement('textarea');
var s=document.createAttribute('style');
s.nodeValue='width:100%;height:100em;';
ta.setAttributeNode(s);
ta.appendChild(document.createTextNode(document.body.innerText));
document.body.appendChild(ta);
ta.focus();
for (var i = 1; i <= ta.value.length; i++)
ta.setSelectionRange(i, i);
}
Code from #JohnLBevan blog post (posted on 2011/03/28)
I made the comment above, then I used the idea from the first answer to add this to my dev environment:
function showPageSource()
{
var text = document.body.innerText;
var textarea = document.createElement('TEXTAREA');
textarea.style.position = 'absolute';
textarea.style.opacity = 0.95;
textarea.style.zIndex = 999;
textarea.style.top = '25px';
textarea.style.left = '25px';
textarea.style.width = 'calc(100% - 50px)';
textarea.style.height = '500px';
textarea.value = text;
document.body.appendChild(textarea);
textarea.addEventListener('click', function (e)
{
e.stopPropagation();
}, false);
document.body.addEventListener('click', function (e)
{
textarea.parentNode.removeChild(textarea);
}, false);
}
And then a tag like this to show the sauce:
SHOW PAGE SOURCE
Shows a fair amount of crap from the navigation - but I can live with that.

What is the " Run <extension> command" in the omnibox? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I have created an extension that integrates with the omnibox. When I have typed in the keyword + space and then the phrase to send to the extension, I can see that the top row in the omnibox says "Run my-extenison-name command:"
What exactly is this? Can I use this somehow to maybe call methods in my extension?
It would be really nice if it was possible, but I can't find any info on this.
"Run <your-extension-name> command" is simply the "Default" default suggestion for your extension's omnibox. It's basically the placeholder for what is currently entered, and should indicate what will happen if the user presses enter at that point ("search my site for 'x'"). To change it, just add this to your background page
chrome.omnibox.setDefaultSuggestion({"description" : "your description here"});
You can use "%s" in there as well as a placeholder for what the user is typing in.
Jason was right in how you can use onInputEntered to react to the user entering something into the omnibox.
When the user selects the command, any listeners you've added to the onInputEntered event will be fired.
See: http://code.google.com/chrome/extensions/omnibox.html#event-onInputEntered
So yes, you can have Omnibox commands call methods in your extension, just by adding a listener to that event, like so:
chrome.omnibox.onInputEntered.addListener(function(text) {
console.log('User entered command: ' + text);
};
You can also get notifications of the user's omnibox activity while they're typing, or if they cancel typing, by adding listeners for the other events listed on the page linked above.
I do this for my Chrome extension Lil’ Launch which has no use for the default suggestion (it only searches your bookmarks).
The full source is on Github, but the general idea is this. The callback for chrome.omnibox.onInputEntered gets passed either the content property of your selection or the value of the user input if the suggestion is the default one. So I append a known string to the front of all the content properties and check for that same string when chrome.omnibox.onInputEntered fires. It needs to be something that the use is unlikely to type, otherwise the matching will break.
var resultsList = [], // Accessible from the callback scope
unlikely = "GOSHDARNYOUCHROME"; // Our unlikely to be typed String
chrome.omnibox.onInputChanged.addListener(
function(text, suggest) {
var searchResults = chrome.bookmarks.search(text, function(searchResults) {
resultsList = [];
for (var i = 0; i < searchResults.length; i++) {
resultsList.push({
content: unlikely + item.url, // Prepend our unlikely string to the URL
description: "bar"
});
};
// Chrome adds a completely useless default suggestion in our case
// So set the default and slice it off the suggestions
chrome.omnibox.setDefaultSuggestion({ description: resultsList[0].description });
suggest(resultsList.slice(1, -1));
})
}
);
chrome.omnibox.onInputEntered.addListener(
function(text) {
// If text doesn't have unlikely prepended its the stupid default
if(text.substring(0, unlikely.length) !== unlikely) {
text = resultsList[0].content;
}
text = text.substring(unlikely.length); // Trim the unlikely string
// Do something with text
}
);
Stupid, but effective.

Resources