Iterate through poorly formated object - javascript

I have a really bad-formated javascript object:
commits = {
commit: {
name: 'First commit'
},
commit: {
name: 'Second commit'
}
}
As you can see, each sub-object of commits object is called commit so it practically precludes an option to use for ... in ... or any other javascript loop (well, that's what i think but i'm a really poor JS programmer so i'm probably wrong). So, the question is, how can i iterate through that object?
Please have in mind that i can't use jQuery here and i can't rewrite that object
edit: that object is parsed from the following json:
{
"commits": {
"commit": {
"name": "First commit"
},
"commit": {
"name": "Second commit"
},
}
}

Considering the JSON posted in the github link you provided, there's not a lot you have to do.
The JSON string seems to be valid, except that it's missing a } at the end of the string. With that fixed, it parses just fine:
JSON.parse('{\n \"accountURL\": \"https://domain.com\",\n \"newCommitsCount\": \"1\",\n \"pushURL\":\"https://domain.com/project/64249/git/source/compare/revisions/0b6438955f2a5a7981fd25cfa5b48fe3fb4c888d,7771e638d1356a14d1dc46f3f5cfaab858370a5e\",\n \"unsubscribeURL\": \"https://domain.com:443/unsubscribe?token=receiverToken&type=COMMITS&projectId=64249\",\n \"invokerEmail\": \"email#email.com\",\n \"projectURL\": \"https://domain.com/project/64249\",\n \"projectId\": \"64249\",\n \"afterPushRevision\": \"7771e638d1356a14d1dc46f3f5cfaab858370a5e\",\n \"invokerId\": \"38074\",\n \"pushDate\": \"2014-02-11T15:26:36+0000\",\n \"beforePushRevision\": \"0b6438955f2a5a7981fd25cfa5b48fe3fb4c888d\",\n \"repositoryURL\": \"git_url\",\n \"subdomain\": \"subdomain\",\n \"domain\": \"domain\",\n \"branch\": \"develop\",\n \"invokerProfileURL\": \"url\",\n \"commitsCount\": \"1\",\n \"invokerSmallAvatarURL\": \"xx\",\n \"projectName\": \"NAME\",\n \"invoker\": \"Invoker Name.\",\n \"commits\": {\"commit\": {\n \"revision\": \"7771e638d1356a14d1dc46f3f5cfaab858370a5e\",\n \"commitMessage\": \"quickfix\",\n \"committerId\": \"38074\",\n \"committerEmail\": \"email\",\n \"committerName\": \"Name.\",\n \"commitDate\": \"2014-02-11T15:26:27+0000\",\n \"commitURL\": \"https://domain.com/project/64249/git/source/commit/develop/7771e638d1356a14d1dc46f3f5cfaab858370a5e\" }}}')

Related

how to loop through array of json objects in angularjs

I have a auto search module with below json structure. I need to loop through aray of json objects and use key and value as per requirements.
I have tried below code. But with provided json object, I am able to retrieve key, but not value.
lets say, for firt, Json object, I need to retrieve 'Product Apple'., but I`m getting only link.
I tried response.data[key][0] ,but getting full json object. May I Know where I have done wrong.
I have updated plunker below
[{
"/folder1/folder2/folder3/product-1": "Product Apple"
},
{
"/folder1/folder2/folder3/product-2": "Product samsung"
},
{
"/folder1/folder2/folder3/product-3": "Product lenovo"
},
{
"/folder1/folder2/folder3/product-4": "Product Asus"
},
{
"/folder1/folder2/folder3/product-5": "Product Acer"
},
{
"/folder1/folder2/folder3/product-6": "Product Vivo"
},
{
"/folder1/folder2/folder3/product-7": "Product Oppo"
}
]
code here
Since this is marked as duplicate post., I have gone through the provided solution and found that the duplicate post has solution via javascript. But I`m looking to iterate through angularjs 'ng-repeat'.
Please find plunker below for solution I have got
[code here][1]
code here
You probably want to assign that structure to a variable, and then run an *ngFor on it, like this:
// in the component file
let results = [
{
"/folder1/folder2/folder3/product-1":"Product Apple"
},
{
"/folder1/folder2/folder3/product-2":"Product samsung"
},
{
"/folder1/folder2/folder3/product-3":"Product lenovo"
},
{
"/folder1/folder2/folder3/product-4":"Product Asus"
},
{
"/folder1/folder2/folder3/product-5":"Product Acer"
},
{
"/folder1/folder2/folder3/product-6":"Product Vivo"
},
{
"/folder1/folder2/folder3/product-7":"Product Oppo"
}
]
// in the view
<ng-container *ngFor="let result of results">
view logic goes here
</ng-container>

How to validate $set 'keys' with MongoDB?

I've got a rather specific case: Using mongoose/mongo and user objects
I want to find and update user in one call.
DB.collection('users').findOneAndUpdate({localId: id} ,{ "$set": { "name": "lla", "usnme": "As"} } ,callback);
Note that 'username' is spelled wrong. Yet mongo updated the first field(name) and does not give any error about the second.
How can I validate the keys I pass in $set without making more than one query?
What MongoDB suggests here is called schema validation:
In your specific case you could run the following command to make sure that no additional ("incorrect") fields can be added by anyone:
db.runCommand({ "collMod": "users", "validator": {
$jsonSchema: {
additionalProperties: false,
properties: {
"_id": {
bsonType: "objectId"
},
"name": {
bsonType: "string"
},
"username": {
bsonType: "string"
}
}
}
}})
Beyond that I cannot really think of any solution since MongoDB is a document database which by default is schemaless and hence won't stop you from creating the fields you tell it to create...

Elasticsearch setting up stemming and analyzer questions

I'm using ES with my node server via the package "elasticsearch": "12.1.3".
I do bulk inserts of my documents. Excerpt:
var body = [];
_.each(rows, function(doc) {
body.push({
update: {
_index: 'mytest',
_type: 'mydoc',
_id: doc.id,
_retry_on_conflict: 3
}
});
body.push({
doc: doc,
doc_as_upsert: true
});
});
client.bulk({
body: body
}, ...
On demand, to individually update documents, I have this in place:
client.index({
index: 'mytest',
type: 'mydoc',
id: doc.id,
body: doc.body
}, ...);
Everything works as expected so far. Now I'm trying to add basic 'light_english' stemming.
Looking at the Docs here
and for the JS package here
I want certain fields in my document to be "fuzzy" matched, therefore I think stemming is the way to go?
It is not clear to me how I would set this up.
Assuming I use the example settings from the link above, would this be the right way to do it:
client.cluster.putSettings({
"settings": {
"analysis": {
"filter": {
"no_stem": {
"type": "keyword_marker",
"keywords": [ "skies" ]
}
},
"analyzer": {
"my_english": {
"tokenizer": "standard",
"filter": [
"lowercase",
"no_stem",
"porter_stem"
]
}
}
}
}
});
And would this then work permanently for my two code examples above, if applied once?
Bonus question: What would be a good default analyzer plugin (or settings) I can use? My main goal is that searches for example: "Günther" would also match "gunther" and vice versa.
Might it be better to do this manually before inserting/updating documents, so that strings are lower-cased, diacritics removed etc.?

Use javascript variable instead json file

here I have a declaration:
<div id="timeline-embed"></div>
<script type="text/javascript">
var timeline_config = {
width: "100%",
height: "100%",
debug: true,
rows: 2,
source: 'Timeline/example_json.json'
}
</script>
<script type="text/javascript" src="Timeline/compiled/js/storyjs-embed.js"></script>
so now I want to instead source: 'Timeline/example_json.json' to use
something like:
source: '{
"timeline":
{
"headline":"Sh*t People Say",
"type":"default",
"text":"People say stuff",
"startDate":"10/4/2011 15:02:00",
"date": [
{
"startDate":"10/4/2011 15:10:00",
"endDate":"10/4/2011 15:55:00",
"headline":"prvo",
"text":"<p>dddddddddddddddd dd</p>",
"asset":
{
"caption":"yessss"
}
},
{
"startDate":"10/4/2011 17:02:00",
"endDate":"10/4/2011 18:02:00",
"headline":"drugo da da",
"text":"<p>In true political fashion, his character rattles off common jargon heard from people running for office.</p>",
"asset":
{
"media":"http://youtu.be/u4XpeU9erbg",
"credit":"",
"caption":""
}
}
]
}
}'
but doesn work. I really dont know what is probem exactly... Please help.
So this is verite Timeline plugin and this plugin need JSON as source, but is there any way to change source with Javascript variable?
The way you have this written, the value of "timeline_config.source" is a String, not a "usable" Javascript object.
You may need to convert the string to an object using JSON.parse(). So add this line of code as the last line of your first < script > block.
timeline_config.source = JSON.parse(timeline_config.source)
Alternatively, as pointed out in the comments, you can simply remove the single quotes around the string, and it will natively by a JS Object.
Try removing the ' string delimiter, so it says
source: {
"timeline": { ... }
},
This way it is a JS object and not a string.

Iteration in handlebar using backbone

I'm using backbone and handlebars for templating and i'm new to this.
My current json is in the below format and the code works fine.
[
{
"id": "10",
"info": {
"name": "data10"
}
},
{
"id": "11",
"info": {
"name": "data11"
}
}
]
But when i change my json structure to something like shown below i'm having difficulty in getting things to be populated.
{
"total_count": "10",
"dataElements": [
{
"id": "10",
"info": {
"name": "data10"
}
},
{
"id": "11",
"info": {
"name": "data11"
}
}
]
}
How can i populate name, info and total_count keeping the current code structure ?
JSFiddle : http://jsfiddle.net/KTj2K/1/
Any help really appriciated.
A few things that you need to do in order for this to work.
Replace Backbone's core 'reset' on your collection with a custom one that understands the data you are passing to it. For example:
reset: function (data) {
this.totalCount = data.total_count;
Backbone.Collection.prototype.reset.call(this, data.dataElements);
}
Now when you reset your collection, it will pull the total_count out of the object you are resetting it with, and use Backbone's core reset with the dataElement array. Keep in mind you may have to do a similar thing with 'parse' if you're intending on pulling this from the server.
I'd recommend that (if your example looks anything like the real code you're working with) you reset your collection before getting to rendering.
var dataCollectionList = new dataCollection();
dataCollectionList.reset(jsonData);
var App = new AppView({model : dataCollectionList});
Now in your view's "render" method you can grab the 'totalCount' property off the collection -
render : function() {
//Should spit the total count into the element, just as an example
this.$el.append(this.model.totalCount);
//or console.log it
console.log(this.model.totalCount);
return this;
}
Voila. Side note - as someone who works with Backbone a lot, it drives me nuts when people set an attribute of something like "model" (i.e. peopleModel, itemModel, etc) and it ends up being a backbone collection. It's much clearer to name it after what it is - though some MVC purists may disagree a bit.
Also, in this code block:
_.each(this.model.models, function (myData) {
$(this.el).append(new ItemView({model:myData}).render().el);
}, this);
You don't need to do _.each(this.model.models.......). Since you're working with a collection, the collection has a built in 'each' method.
this.model.each(function (myData) { ..... } , this);
Quite a bit cleaner.

Categories

Resources