access to json multidimensional array with react - javascript

I'm trying to access a certain element of my JSON, through React JS i use: Object.keys(field)[0] on the json and I get "punteggio" but I would like to get its value instead, for example "7". How can I access to this data?
"honours": [
{
"punteggio" : 7,
"serie" : "Serie A",
"tipo" : "icon-scudetto",
"anni" : "1926/1927 revocato, 1027/1928, 1942/1943, 1945/1946, 1947/1948"
},
{
"punteggio" : 4,
"serie" : "Serie B",
"tipo" : "icon-scudetto",
"anni" : "1958/1960, 1989/1990, 2000/2001, 2011/2012"
},
{
"punteggio" : 5,
"serie" : "Serie B",
"tipo" : "icon-coppaitalia",
"anni" : "1958/1960, 1989/1990, 2000/2001, 2011/2012"
}
]

"punteggio" - is just a key, so you can access its value like this
const key = Object.keys(field)[0];
const value = field[key];

Object.Keys used when you need to fetch key of array from the object
use Object.Values to fetch the value
Read more at :
https://javascript.info/keys-values-entries

Related

Modify existing json file using nodejs

I have a json file named a1.json->(It has the following structure)
{ "Key1" :
[ {
"Key11" : "Value11" ,
"Key12" : "Value12"
},
{
"Key21" : "Value21" ,
"Key22" : "Value22"
}
]
}
I am iterating through a data file which has certain values. If the values match i will have to add an extra key to that particular dictionary only. For example-
{ "Key1" :
[ {
"a" : "A1" ,
"b" : "B1"
},
{
"a" : "A2" ,
"b" : "B2"
}
]
}
I want to add a key value pair in that list whose key value "a" is "A1". So the final result will look something like this-
{ "Key1" :
[ {
"a" : "A1" ,
"b" : "B1" ,
"New_Key_Array" :
[
{
"Found" : "yes",
"Correctness" : "true"
}
]
},
{
"a" : "A2" ,
"b" : "B2"
}
]
}
How do I go about this. I am a bit new to JSON formatting and still learning how to edit existing JSON files?
You can use JSON.parse() to parse your json file/string into a JavaScript object. In your example:
let j = JSON.parse('{ "Key1" :[ { "a" : "A1" , "b" : "B1"},{"a" : "A2" , "b" : "B2"}]}');
To add a new key to your object, it's possible with native JavaScript code, if that's what you want:
j.Key1[0]["New_Key_Array"] = [ { Found: "yes", Correctness: "true" } ];
To convert back into json formatted string, you can use the JSON.stringify() function.
I am providing a code snippet for your problem:
let j = JSON.parse('{ "Key1" :[ { "a" : "A1" , "b" : "B1"},{"a" : "A2" , "b" : "B2"}]}');
console.log("JSON at the beginning:\n", j);
j.Key1.forEach((element, index) =>{
if(element.a === "A1"){
//Here I have to edit the JSON obj
j.Key1[index]["New_Key_Array"] = [ { Found: "yes", Correctness: "true" } ];
}
});
console.log("JSON edited:\n ",j);
let objString =JSON.stringify(j);

Find nested property from ember lodash and pick the value

I am new to javascript.
I would like to check whether the specific nested property is present or not in an array of items, ex)
[{
"_id" : ObjectId("5c4ec057e21b840001968d31"),
"status" : "ACTIVE",
"customerId" : "sample-book",
"bookInfo" : {
"bookChunks" : [
{
"key" : "Name",
"value" : "test"
},
{
"key" : "Surname1",
"value" : "testtt"
},
{
"key" : "user-contact",
"value" : "sample-value",
"ContactList" : {
"id" : "sample-id",
"timeStamp" : "Tue, 20 Sep 2016 07:49:25 +0000",
"contacts" : [
{
"id" : "contact-id1",
"name" : "Max Muller",
"phone_number" : "+XXXXXXX"
},
{
"id" : "contact-id2",
"name" : "Max Muller",
"phone_number" : "+XXXXXXX"
}
]
}
}
]
}
},
{
"_id" : ObjectId("5c4ec057e21b840001968d32"),
"status" : "ACTIVE",
"customerId" : "sample-book1",
"bookInfo" : {
"bookChunks" : [
{
"key" : "Name",
"value" : "test"
},
{
"key" : "Surname1",
"value" : "testtt"
}
]
}
}]
Here, I would like to find whether any item has ContactList or contacts present. If it is present take the item and put it in a separate list.
I am using ember-lodash. Using normal javascript or lodash would be fine for me. Any help will be really appreciated.
You could use filter and some. This returns all the objects which have at least one object with ContactList property inside bookInfo.bookChunks array.
const input=[{"_id":"5c4ec057e21b840001968d31","status":"ACTIVE","customerId":"sample-book","bookInfo":{"bookChunks":[{"key":"Name","value":"test"},{"key":"Surname1","value":"testtt"},{"key":"user-contact","value":"sample-value","ContactList":{"id":"sample-id","timeStamp":"Tue, 20 Sep 2016 07:49:25 +0000","contacts":[{"id":"contact-id1","name":"Max Muller","phone_number":"+XXXXXXX"},{"id":"contact-id2","name":"Max Muller","phone_number":"+XXXXXXX"}]}}]}},{"_id":"5c4ec057e21b840001968d32","status":"ACTIVE","customerId":"sample-book1","bookInfo":{"bookChunks":[{"key":"Name","value":"test"},{"key":"Surname1","value":"testtt"}]}}]
const output = input.filter(o =>
o.bookInfo.bookChunks.some(c => "ContactList" in c)
)
console.log(output)
If you just want to check if any of the objects have ContactList, you could replace filter with another some
(Note: This assumes that bookInfo.bookChunks will not be undefined. Otherwise you'd have to add a undefined check before using the nested property)

Mongoose find returns document instead of specific object in array

When I try to find specific object in array using find({query}) I always get all elements from array.
Activities array stores activities (it would be a thousands of them) as you can see in the following snippet:
This is my collection:
{
"_id" : ObjectId("58407140755324d04db2ce95"),
"owner" : 103429326776572,
"activities" : [
{
"name" : "test1",
"startTime" : ISODate("2016-08-11T17:41:54Z"),
"type" : "te1",
"lat" : 1,
"lon" : 1,
"creator" : 126212904493088,
"coverPhoto" : {
"name" : "test1",
"path" : "c:\\Users\\Francis\\Desktop\\dusk\\public\\coverPhotos\\SJ9tpP6Mx.jpg"
},
"identifier" : "H1g9F6vpGl",
"users" : [
1,
2,
3
],
"hashTags" : [
"some",
"hashtags"
]
},
{
"name" : "test2",
"startTime" : ISODate("2016-08-11T17:41:53Z"),
"type" : "te2",
"lat" : 1,
"lon" : 1,
"creator" : 103312904493090,
"coverPhoto" : {
"name" : "test2",
"path" : "c:\\Users\\Francis\\Desktop\\dusk\\public\\coverPhotos\\Hy8qpvafe.jpg"
},
"identifier" : "rJlU5TvpMx",
"users" : [
1,
2,
3
],
"hashTags" : [
"some",
"hashtags"
]
}
]
}
I need to get for example an activity that has specific identifier.
I tried to use queries like:
1) db.myCollection.find({'activities.identifier' : "rJlU5TvpMx"})
2) db.myCollection.find({'activities' : { $elemMatch : { "identifier" : "rJlU5TvpMx", "creator" : 103312904493090 } })
And all combinations with '' or "" signs
I found above queries at mongodb docs in equal documents schema as mine is.
Can you tell me what am I doing wrong ?
You can try either use single match or multiple match based on your need. This makes use of $elemMatch(projection)
db.myCollection.find({"_id" : ObjectId("58407140755324d04db2ce95")},
{activities: {$elemMatch: { identifier: "rJlU5TvpMx"}}})
db.myCollection.find( {"_id" : ObjectId("58407140755324d04db2ce95")},
{activities: {$elemMatch: {creator : 103312904493090, identifier: "rJlU5TvpMx" }}})
You are looking for the projection object which gets passed as an argument in your query. It allows the return of specific fields from your search rather than the entire document. http://mongoosejs.com/docs/api.html#model_Model.find
I would also suggest looking at the response to this question here: Mongoose Query: Find an element inside an array which makes use of the unwind operator to enter the array as it seems to be relevant to your needs.
In the collection you are searching in, you have just one Document(Object). If you apply method find() to your collection and the query inside matches the value in activities.identifier it will return the only Document(object).
To have a better understanding of what I am talking about check example on mongoose API doc
And query result here.
Try check this out https://docs.mongodb.com/v3.0/reference/operator/projection/elemMatch/#proj._S_elemMatch instead

How to check if array contains a value in Javascript

I have a json object which has an array property 'partners' like below:
{
"_id" : ObjectId("578667b1bb14ca1c2773adaa"),
"customer" : null,
"created" : ISODate("2016-07-13T16:09:21.015+0000"),
"description" : "",
"subject" : "case 2",
"__v" : NumberInt(5),
"partners" : [
ObjectId("57857d93038aacd81ef3ad55"),
ObjectId("57857d93038aacd81ef3ad56")
]
}
I would like to check if an element already exists on the partner array using the following code:
_.includes(case_.partners, partner._id)
Just so u know I am using lodash for this but for some reason is not working and I have no clue why, anyone knows what is the problem here?
What I understanding, the partners sample you provided, is an javascript object, you should try to use primitive type value in the Json.
You can convert ObjectId to String by these way:
ObjectId("578667b1bb14ca1c2773adaa") + '';
or
ObjectId("578667b1bb14ca1c2773adaa").toHexString();
The Json object should be like this:
{
"_id" : "578667b1bb14ca1c2773adaa",
"customer" : null,
"created" : "2016-07-13T16:09:21.015+0000",
"description" : "",
"subject" : "case 2",
"__v" : 5,
"partners" : [
"57857d93038aacd81ef3ad55",
"57857d93038aacd81ef3ad56"
]}
So the solution will be , convert Javascript object into Json object, and then compare them.

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!

Categories

Resources