Add new element to array with setState - javascript

How to add new element to array with setState
I have this data
this.state = {
items : [
{ "id" : "324", "parent" : "qqqq", "text" : "Simple root node" },
{ "id" : "24", "parent" : "dwdw", "text" : "Root node" },
{ "id" : "55", "parent" : "ajson2", "text" : "Ch" },
{ "id" : "9866", "parent" : "ajson2", "text" : "oiiojio" },
]
}
I'm mapping the data
{this.state.items.sort((a,b) => a.newID < b.newID).map((item)=>
<ul>
<li key={item.id}><span>ID: </span>{item.id} <span>parent: </span>{item.parent} <span>text: </span>{item.text}</li>
</ul>
)}
and then I'm sorting the data by newID That I need to create it with setState
this.setState(prevState=>({newData: [...prevState.items, this.props.account.info]}));
How can I create new element with this.props.account.info add somthing like i++ I don't know actually
this.props.account.info It's adding data like
{ "id" : "324", "parent" : "qqqq", "text" : "Simple root node" }
So I need to add an element inside this will be like
{ "newID": "1", "id" : "324", "parent" : "qqqq", "text" : "Simple root node" }

So if you want to add "newID" field in the object, there is a way to do this using object spread operator.
{...this.props.account.info, "newID":"1"}
This will give you a new object with the "newID" field added with "1" as its value associated with it.
This is a shorthand for this:
Object.assign({}, this.props.account.info, {"newID": "1"});

Related

add to my nested json doesn't work correctly

I am trying to "ADD" a new key "resource1" to my below JSON.
I tried jsonFile["entry"][2] = "resource1" . This worked.
Now i want to add an object with "resourceType", "code", "subject"...... like how it is displayed for "resource" in my json below. How do i achieve this???
Like this --> jsonFile["entry"][2]["resource1"] = {"resourceType" : "Observation"} ?????
Need help here
jsonFile:
{
"resourceType" : "Bundle",
"type" : "transaction",
"entry" : [
{
"fullUrl": "urn:uuid:patient",
"resource" : {
"resourceType" : "Patient",
"name" : [
{
"given": ["Lola"],
"family": "Tes"
}
]
},
"request" : {
"method" : "POST",
"url" : "Patient"
}
},
{
"resource" : {
"resourceType" : "Observation",
"code" : {
"coding" : [
{
"system": "http://loinc.org",
"code": "15074-8",
"display": "Glucose [Moles/volume] in Blood"
}
]
},
"subject": {
"type" : "Patient",
"reference" : "urn:uuid:patient"
},
"valueQuantity": {
"value": "5",
"unit": "mmol/l",
"system": "http://unitofmeasure.org",
"code": "mmol/L"
}
},
"request" : {
"method" : "POST"
}
}
]
}
Looks like you are trying to add the property to non existing object.
From your example.
jsonFile["entry"][2] = "resource1"
this worked because you are adding this to existing property(i.e. jsonFile has entry object which is array. So, it's just simply pushing this to array.
But when you are trying this,
jsonFile["entry"][2]["resource1"] = {"resourceType" : "Observation"}
it's trying to add property to non extsting object(i.e. jsonFile has entry, but entry has only 0 and 1 position objects in array. So, this will throw error.
To add property at 2nd position, you need to initialise object at that position and then you can add property.
You can do it in following ways,
jsonFile["entry"][2] = {}
jsonFile["entry"][2]["resource1"] = {"resourceType" : "Observation"}
Or
jsonFile["entry"][2] = {"resource1":{"resourceType" : "Observation"}}
You can add property to object if and only if that object is exists.

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)

"Evaluate" Function that is stored in MongoDB Server

My collection looks like this:
> db.projects_columns.find()
{ "_id" : "5b28866a13311e44a82e4b8d", "checkbox" : true }
{ "_id" : "5b28866a13311e44a82e4b8e", "field" : "_id", "title" : "ID", "sortable" : true }
{ "_id" : "5b28866a13311e44a82e4b8f", "field" : "Project", "title" : "Project", "editable" : { "title" : "Project", "placeholder" : "Project" } }
{ "_id" : "5b28866a13311e44a82e4b90", "field" : "Owner", "title" : "Owner", "editable" : { "title" : "Owner", "placeholder" : "Owner" } }
{ "_id" : "5b28866a13311e44a82e4b91", "field" : "Name #1", "title" : "Name #1", "editable" : { "title" : "Name #1", "placeholder" : "Name #1" } }
{ "_id" : "5b28866a13311e44a82e4b92", "field" : "Name #2", "title" : "Name #2", "editable" : { "title" : "Name #2", "placeholder" : "Name #2" } }
{ "_id" : "5b28866a13311e44a82e4b93", "field" : "Status", "title" : "Status", "editable" : { "title" : "Status", "type" : "select", "source" : [ { "value" : "", "text" : "Not Selected" }, { "value" : "Not Started", "text" : "Not Started" }, { "value" : "WIP", "text" : "WIP" }, { "value" : "Completed", "text" : "Completed" } ], "display" : "function (value, sourceData) { var colors = { 0: 'Gray', 1: '#E67C73', 2: '#F6B86B', 3: '#57BB8A' }; var status_ele = $.grep(sourceData, function(ele){ return ele.value == value; }); $(this).text(status_ele[0].text).css('color', colors[value]); }", "showbuttons" : false } }
You can see that in the very last document that I have stored a function as text.Now the idea is that I will request this data and will be in an Javascript Array format.
But I want to be able to have my function without the quotes! You can see that simply evaluating it will not work because I need to have it still needs to be inside of the object ready to be executed when the array is used.
How can I achieve this?
Thanks for any help!
There are two possible solutions, but neither particularly safe and you should strongly consider why you need to store functions as strings in the first place. That being said, you could do two things.
The simplest is to use eval. To do so, you would have to first parse the object like normal, and then set the property that you want to the result of eval-ing the function string, like so:
// Pass in whatever JSON you want to parse
var myObject = JSON.parse(myJSONString);
// Converts the string to a function
myObject.display = eval("(" + myObject.display + ")");
// Call the function with whatever parameters you want
myObject.display(param1, param2);
The additional parentheses are to make sure that evaluation works correctly. Note, that this is not considered safe by Mozilla and there is an explicit recommendation not to use eval.
The second option is to use the Function constructor. To do so, you would need to restructure your data so that you store the parameters separately, so you could do something like this:
var myObject = JSON.parse(myJSONString);
// displayParam1 and displayParam2 are the stored names of your parameters for the function
myObject.display = Function(myObject.displayParam1, myObject.displayParam2, myObject.display)
This method definitely takes more modification, so if you want to use your existing structure, I recommend eval. However, again, make sure that this is absolutely necessary because both are considered unsafe since outside actors could basically inject code into your server.

Get all parent documents in a mongoDB model tree structure

I'm using a model tree structure for my collection. As references I'm using parent-fields. I need to get attributes from the current object and all its parents. The last element in a path has a field 'target'. So I start with
var result = parent = Articles.findOne({target: this.params._id});
do {
parent = Articles.findOne({_id: parent.parent}).parent;
for (var attrname in parent) { result[attrname] = parent[attrname]; }
}
while (parent.parent === null);
That seems to be very inefficient to me. Isn't it possible to do that with one line to get an object with all elements? Then I could process that object.
Example documents
{
"_id" : "LD6h5ZcDuJjexfKfx",
"title" : "title",
"publisher" : "public",
"author" : "author"
}
{
"_id" : "KSiyh8zHRq8RZQ2E6",
"edition" : "edition",
"year" : "2020",
"parent" : "LD6h5ZcDuJjexfKfx"
}
{
"_id" : "5yCk4y25wrLBLZhyY",
"pageNumbers" : "1-10",
"target" : "9sjhzPhyTuQ5Kbh6v",
"parent" : "KSiyh8zHRq8RZQ2E6"
}
So starting with "target" : "9sjhzPhyTuQ5Kbh6v" I would like to get the two parent documents (in this example).
At least I need the dataset
"title" : "title",
"publisher" : "public",
"author" : "author",
"edition" : "edition",
"year" : "2020",
"pageNumbers" : "1-10"
If you want to do this in a single query then you need to follow the array of ancestors pattern in Mongodb. Otherwise you need to recursively traverse the branches above the leaf node as you are doing. For hierarchies with low depth such as yours this is not a big penalty.
With an array of ancestors your doc tree would look like:
{
"_id" : "LD6h5ZcDuJjexfKfx",
"title" : "title",
"publisher" : "public",
"author" : "author",
}
{
"_id" : "KSiyh8zHRq8RZQ2E6",
"edition" : "edition",
"year" : "2020",
"ancestors" : ["LD6h5ZcDuJjexfKfx"],
"parent" : "LD6h5ZcDuJjexfKfx"
}
{
"_id" : "5yCk4y25wrLBLZhyY",
"pageNumbers" : "1-10",
"target" : "9sjhzPhyTuQ5Kbh6v",
"ancestors" : ["LD6h5ZcDuJjexfKfx","KSiyh8zHRq8RZQ2E6"],
"parent" : "KSiyh8zHRq8RZQ2E6"
}
To get the doc and its parents:
Articles.find({ $or: [ { target: target },
_id: { $in: Articles.findOne({ target: target }).ancestors }]});

jstree get data after update

I pass some json data in jstree and then I update the tree.
For example my initial data is
[
{ "id" : "demo_root_1", "text" : "Root 1", "children" : true, "type" : "root" },
{ "id" : "demo_root_2", "text" : "Root 2", "type" : "root" }
]
I update it a little (simple rename). "Root 1" becomes "UPDATED". How can I get the updated version of my data in json format like below?
[
{ "id" : "demo_root_1", "text" : "UPDATED", "children" : true, "type" : "root" },
{ "id" : "demo_root_2", "text" : "Root 2", "type" : "root" }
]
Okay..so basically if you want to refresh the tree with the updated data, then after the updation code, call the jstree callback:
$(tree).jstree('refresh');
This will refresh the tree with the new json data.
let me know in case of further issues.

Categories

Resources