Accessing data from Object Javascript - javascript

I have created this object :
var hemicycle = {
Groupe : "Group1" [{
Member : [{
Name : "MemberName",
Siege : "SiegeNumber",
Vignette : "PhotoURL"
}]
}]
};
I try to display some data from it but I can't access any.
When I type hemicycle in the dev tools of Chrome I get this :
I also tried to display "Group1" from the object but it won't let me, I typed this :
I don't know why my object is not defined ?
Any help is appreciated.

Well, the issue is, that you actually don't have a valid object. Groupe has really weird structure, what is it supposed to be? Array? Then try this:
var hemicycle = {
Groupe: [{
Member : [{
Name : "MemberName",
Siege : "SiegeNumber",
Vignette : "PhotoURL"
}]
}]
};

Your problem is that your object itself is invalid.
Two ways to improve that. Choose whatever fits your needs best.
var hemicycle = {
Groupe : "Group1",
Content : [{
Member : [{
Name : "MemberName",
Siege : "SiegeNumber",
Vignette : "PhotoURL"
}]
}]
};
var hemicycle = {
Groupe : [{
Member : [{
Name : "MemberName",
Siege : "SiegeNumber",
Vignette : "PhotoURL"
}]
}]
};

this simple example should solve your problem
var myObj = {
"1": { address: "44 buxton gardens berea durban", lat: "25.686", lng: "58.1156"},
"2": { address: "44 buxton gardens berea durban", lat: "0.0086", lng: "-0.00056"}
}
alert(myObj['1']['address']); //this get the address value of the first element
//using foreach statement to access the element and key
for (key in myObj){
alert(key); //this will display the 1
//use can say
alert(myObj[key]['address']); // this gets the value of address
}

Related

Javascript - Update value in nested dictionary regardless of depth

Hi first of all I would like to state that yes, this question has been answered here Update value of a nested dictionary of varying depth however, this is in Python.
I would like to know if there's a Javascript approach to solving this issue.
Let's say I have a dictionary as such:
{
"group1" : {
"name" : "NAME1"
},
"group2" : {
"name" : "NAME2"
}
}
How would I be able to replace "NAME1" with lets say "Bob White" without doing this dict["group1"]["name"] = "Bob White"?
Could someone help please? Thanks
You can loop through each property and set the value of its name property:
const obj = {
"group1" : {
"name" : "NAME1"
},
"group2" : {
"name" : "NAME2"
}
}
Object.keys(obj).forEach(e => obj[e].name = "Bob White")
console.log(obj)

Accessing arrays

I'm using the Raphaël framework to draw dynamic shapes (which make them clickeable, you can make them glow...).
I can't access the array correctly.
I've created an array :
var siegeurs = {
1 : [{
"Nom" : "User1",
"Photo" : "url"
}],
2 : [{
"Nom" : "User2",
"Photo" : "url"
}],
3 : [{
"Nom" : "User3",
"Photo" : "url"
}],
4 : [{
"Nom" : "User4",
"Photo" : "url"
}],
5 : [{
"Nom" : "User5",
"Photo" : "url"
}]
};
These are the shapes that the framework draw :
sieges["1"] = assembly.path("M236.51 ... 108");
sieges["2"] = assembly.path("M483.51 ... 71");
sieges["3"] = assembly.path("M427.51 ... 272");
sieges["4"] = assembly.path("M135.51 ... 348");
sieges["5"] = assembly.path("M617.51 ... 413");
They are like object so you can interact with them.
This is the loop :
for(var siegeNum in sieges) {
(function (siege) {
siege.attr(style); //apply style to shapes
siege[0].addEventListener("mouseover", function() {
siege.animate(hoverStyle, animationSpeed); //add hoverstyle when hovered
//The line I can't figure out
document.getElementById("textelement").innerHTML = siegeurs[siegeNum]["Nom"];
//The line I can't figure out
}, true);
siege[0].addEventListener("mouseout", function() {
siege.animate(style, animationSpeed);
document.getElementById("textelement").innerHTML = baseTxt;
}, true);
})
(sieges[siegeNum]);
}
textelement is a basic text I try to modify when a shape is hovered.
Actually, when I hover a shape, the text goes to "undefined".
I tried to do this way just to check :
document.getElementById("textelement").innerHTML = siegeurs[siegeNum];
But when I hover, the text goes to [object Object].
Any help is appreciated.
Each value in your siegeurs object is an array, so the needed inner property "Nom" should be accessed as:
...
document.getElementById("textelement").innerHTML = siegeurs[siegeNum][0]["Nom"];

Adding Objects to Array of Objects in a Document using Mongoose.js

I've looked in stackoverflow, however I've not found the answer. I'm trying to add Object to a New(empty) Array in my local mongodb that is not a duplicate. I also want to update this Array with other Objects.
I've looked at $push and $addToSet, the examples are using an "id" (_id) which wouldn't be created until I add my first Object.
I'm using Node.js, Mongoose.js, Mongodb, Express.js.
My Schema is:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var barSchema = new Schema({
location: [{
name: String,
city: String,
total: Number
}]
});
var Bar = mongoose.model('Bar', barSchema);
module.exports = Bar;
I've tried to use this;
var newBar = bar({
location: [{ "name": req.body.bar, "city": req.body.city, "total": 0 }] });
newBar.save(function(err) {
if (err) throw err;
});
I've also used the $push with success but in this case I've not got an "id"
user.findByIdAndUpdate(req.user._id, { $push: {
barlist: { "name": req.body.bar,
"rsvp": true } } },
function(err, user) { });
Which gives back this;
{
"_id" : ObjectId("######"),
"location" : [
{
"name" : "1st Bar",
"city" : "Boston",
"total" : 0,
"_id" : ObjectId("#########")
}
],
"__v" : 0
}
{
"_id" : ObjectId("######"),
"location" : [
{
"name" : "2nd Bar",
"city" : "Boston",
"total" : 0,
"_id" : ObjectId("#########")
}
],
"__v" : 0
}
However I am trying to get this;
{
"_id" : ObjectId("#######"),
"location" : [
{
"name" : "Biddy Early's",
"city" : "Boston",
"total" : 0
},
{
"name" : "Some Bar Name",
"city" : "Boston",
"total" : 0
}
]
}
Please know there may be better ways to do this, but... The first thing you want to do in this case is create a new instance of your schema or 'model'. Based on what your code looks like you might want to consider something like this;
var newBar = bar({
"city": req.body.city,
location: [{
"bar": req.body.bar,
"total": 0
}]
});
newBar.save(function(err) {
if (err) throw err;
});
Since if you are looking for bars or restaurants in the same city you might want to have a common key/value pair to '.find()' or '.update()' depending on what you want to do with it.
From here, you will want to look into what you mentioned before with '$addToSet' so that you wouldn't be adding duplicate bars to your 'location' array. So for instance;
bar.findOneAndUpdate({'city':req.body.city},
{'$addToSet': { location: {
'bar': req.body.bar, 'total': 0 } } },
function(err, b) {
if (err) throw err;
console.log(b);
});
Consider using a strategy like if/else to determine if the city name exists, if it does then you would utilize the '$addToSet'. Else, if it didn't exist you would utilize the new model like the example I used.

manage neo4j cross relationship in d3.js

I start recently to work with Neo4j database and i'm trying to display a graph using d3js (i'm new with it too!).
For my test i used the movie example data include in neo4j.
Using JQuery ajax and neo4j REST API, i find a way to make it more or less work.
But currently i can't make an actor link to several movie (or i duplicate them!).
here is currently my Cypher request:
match (a)-[r]->(m) RETURN {id: id(m), name: m.title}, collect({name : a.name, id: id(a)})
and the answer i get look like this:
{
"columns" : [ "{id: id(m), name: m.title}", "collect({name : a.name, id: id(a)})" ],
"data" :
[
[
{ "id" : 3, "name" : "The Matrix Reloaded" },
[
{ "id" : 5, "name" : "Keanu Reeves" },
{ "id" : 6, "name" : "Laurence Fishburne" },
{ "id" : 7, "name" : "Carrie-Anne Moss" }
]
],
[
{ "id" : 4, "name" : "The Matrix Revolutions" },
[
{ "id" : 5, "name" : "Keanu Reeves" },
{ "id" : 6, "name" : "Laurence Fishburne" },
{ "id" : 7, "name" : "Carrie-Anne Moss" }
]
],
[
{ "id" : 2, "name" : "The Matrix" },
[
{ "id" : 5, "name" : "Keanu Reeves" },
{ "id" : 6, "name" : "Laurence Fishburne" },
{ "id" : 7, "name" : "Carrie-Anne Moss" }
]
]
]
}
So i'm thinking of 2 workarounds : either i find a way in d3 to do it (but i have a real hard time to understand d3js for this) or i change my cypher request to get the relationship in a different way.
i can of course make a huge workaround in javascript but my objective is to keep the code as much effective as possible (at the end i want to use it to get a lot of data).
i use the example here : http://bl.ocks.org/mbostock/1093130
where i modify the flatten function like this (and some other minor change) :
// Returns a list of all nodes under the root.
function flatten(root) {
var nodes = [], i = 0;
root.data.forEach(function(l) {
var childrenlist = [];
l[1].forEach(function(actor) {
var ac = { name: actor.name, id: actor.id };
childrenlist.push(ac);
nodes.push(ac);
});
var movie = { id: l[0].id, name: l[0].name, children: childrenlist };
nodes.push(movie);
});
return nodes;
}
/*! end of flatten */
So ! since i have a hard time with d3js, i'm looking a way to make my cypher request to give me the relationship info in a different way. more like this example : http://bl.ocks.org/mbostock/4062045
i'm really stuck because i don't know how to build my cypher request!
i'm looking for a way to get the relationship source and destination node id and the node list but i don't know how to do both!
i want to mix this 2 requests:
match (a)-[r]->(m) RETURN {id: id(m), name: m.title}}
and something like this (but i don't know how to get relationship source and dest):
match (a)-[r]->(m) RETURN {src: id(r.src), dst: id(r.dst)}
if you could help me it would be awesome ! i hope i'm clear enough.
of course i'm open to any other suggestions or leads!
Thanks in advance!

Dojo - Dijit.Tree - Updating Tree

I created a simple tree based on a TreeStoreModel which is backed by ItemFileWriteStore.
I tried updating my tree by deleting and adding items to the store as below, but could not.
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dijit.Tree");
dojo.addOnLoad(function () {
var tmpData = [{
"name" : "Dell",
"type" : "business",
"businessid" : "1",
"projectid" : "1",
"submenu" : [{
"name" : "OTP",
"type" : "product",
"productid" : "100"
}
]
}
];
var tmpData1 = [{
"name" : "Lenovo",
"type" : "business",
"businessid" : "1",
"projectid" : "1",
"submenu" : [{
"name" : "OTP",
"type" : "product",
"productid" : "100"
}
]
}
];
var store = new dojo.data.ItemFileWriteStore({
data : {
label : 'name',
items : tmpData
}
});
var treeModel = new dijit.tree.TreeStoreModel({
store : store,
query : {
type : 'business'
},
childrenAttrs : ["submenu"]
});
var divTestTree = dojo.create("div", null, dojo.body(), "first");
var mytree = new dijit.Tree({
model : treeModel
},
divTestTree);
/* Tree is created at this point */
/* Delete the item from the store, for some reason tempData is being reset*/
store.deleteItem(tmpData[0]);
/* save */
store.save();
/* Tree shows up no more at this point */
/* Try adding new item to the store */
store.newItem(tmpData1[0]);
/* save */
store.save();
/*nothing happens! */
});
I followed the lead from here, I must be missing something very trivial here. Please help.
Taken from that page
How do I refresh a Tree from the store?
This isn’t supported. The store needs to notify the tree of any changes to the data. Currently this is really only supported (out of the box) by dojo.data.ItemFileWriteStore, as setting up a client-server dojo.data source where the server notifies the client whenever the data has changed is quite complicated, and beyond the scope of dojo, which is a client-only solution.
The only way to update the tree is to re-draw it again :(
For anyone coming here looking for a solution the problem, 'I suspect there is a bug' is the only answer I got in the forum, so may be this is a bug - goo.gl/M7xg7

Categories

Resources