I have the following problem. I'm sure the solution is rather simple, but I just can't figure it out.
So there is a object which goes like this:
var products = {
"productType1" : {
"productCode" : {
"name" : "Some Name 1",
"price" : "250"
},
"productCode2" : {
"name" : "Some Name 2",
"price" : "300"
},
"productCode3" : {
"name" : "Some Name 3",
"price" : "330"
}
}
}
And I try to match a "productCode" property in a "for in" loop with a variable. And then I just try to access the "name" or "price" property but in return I only get "undefined", although I do get match with a "productCode" property.
for(a in products.productType1){
if(finalCode === a){
console.log(a.name);
break;
}
else{
console.log("This is not the property you're looking for");
continue;
}
So the question is - how can I access the above mentioned properties in a loop?
a is a string containing the property name. It isn't the value of that property. You need to get the value first.
products.productType1[a].name
Related
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)
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)
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.
Im trying to access some data and keep getting errors no matter what I try. Please help.
"rain":{"3h":13.625} is the part of the JSON file I am trying to access.
Here is what I have tried:
var currentRain = data.rain.3h; Which is most logical as it worked before but the number is what is giving the error.
var currentRain = data.rain["3h"];
var currentRain = data.rain[0]["3h"];
var currentRain = data.rain["3h"][0];
UPDATE:
This is the JSON payload:
{ "base" : "stations",
"clouds" : { "all" : 92 },
"cod" : 200,
"coord" : { "lat" : -33.850000000000001,
"lon" : 151.22
},
"dt" : 1429558616,
"id" : 6619279,
"main" : { "grnd_level" : 1024.97,
"humidity" : 100,
"pressure" : 1024.97,
"sea_level" : 1031.0999999999999,
"temp" : 288.77699999999999,
"temp_max" : 288.77699999999999,
"temp_min" : 288.77699999999999
},
"name" : "City of Sydney",
"rain" : { "3h" : 13.625 },
"sys" : { "country" : "AU",
"message" : 0.0101,
"sunrise" : 1429474880,
"sunset" : 1429514809
},
"weather" : [ { "description" : "heavy intensity rain",
"icon" : "10n",
"id" : 502,
"main" : "Rain"
} ],
"wind" : { "deg" : 157.5,
"speed" : 8.3200000000000003
}
}
You'll need to use ["bracket notation"] to access this, since "3h" begins with a number. As MDN explains:
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation.
This is the correct JSON:
{
"rain": {
"3h": 13.625
}
}
First you need to parse it and transform into an object:
var jsonToObject = JSON.parse('{"rain":{"3h":13.625}}');
You can now access it like this:
jsonToObject.rain["3h"]
Just use data["rain"]. If you need to parse it first do JSON.parse(data) and then data["rain"].
OUTPUT
console.log(data["rain"]);
> { '3h': 13.625 }
...keep in mind that will return an Object.
I have this data:
{
"_id" : ObjectId("5461e16ee7caf96f8f3584a2"),
"num_marcacao" : "100",
"sexo" : "Fêmea",
"idade" : "20",
"bigdata" : {
"abortos" : [
{
"data_aborto" : "2014-11-11",
"causa_aborto" : "Aborto causa 1"
},
{
"data_aborto" : "2014-09-01",
"causa_aborto" : "Aborto causa 2"
}
],
"crias" : [
ObjectId("5461e16ee7caf96f8f3584a2")
]
}
}
{
"_id" : ObjectId("5461e1cae7caf96f8f3584a4"),
"num_marcacao" : "200",
"sexo" : "Fêmea",
"bigdata" : {
"crias" : [
ObjectId("5461e1f3e7caf96f8f3584a5"),
ObjectId("5461e760e7caf96f8f3584a6")
]
}
}
Using the following distinct function I get one result
db.animal.distinct('_id', {'bigdata.crias':{$exists:true}}
Result:
{
"0" : ObjectId("5461e16ee7caf96f8f3584a2"),
"1" : ObjectId("5461e1cae7caf96f8f3584a4")
}
Now I want to get the array that is in bigdata.crias like the result of the distinct query.
I'm trying to do like this:
db.animal.find(
{
$and: [
{'num_marcacao': '200'},
{'bigdata.crias':{$exists: true}}
]
},
{
'bigdata.crias': true,
'_id': false
}
)
But the result is not like the one I need. This is what it's returning:
{
"bigdata" : {
"crias" : [
ObjectId("5461e1f3e7caf96f8f3584a5"),
ObjectId("5461e760e7caf96f8f3584a6")
]
}
}
And I need
{
"0" : ObjectId("5461e1f3e7caf96f8f3584a5"),
"1" : ObjectId("5461e760e7caf96f8f3584a6")
}
Anyhow. MongoDB does not generally do this from either the .find() or .aggregate() methods or anything general around them. Only the .distinct() method invokes a special form where the result given is "truly" just an array of the specified "key" to be distinct on.
You can always "inspect" the object returned and just use the array element in the structure. You can also specify a "query" argument to the .distinct() command method in the first place:
db.collection.distinct(
"bigdata.crias",
{
"bigdata.crias": { "$exists": true },
"num_marcacao": "200"
}
);
Where you also see your $and argument is redundant. All MongoDB query arguments are an "and" implementation by default. You don't need this unless you are specifying "more than one" condition on the same "field name". That would result in an invalid object by breaking the basic "hash/map" "unique key" rule, and which is why and "array" is used for this form to keep it valid.