I'm using const in a function to define a few variables as follows
const printBlock.format({
name : this.matchedData.clientName,
date : this.matchedData.jobDate,
destination : this.matchedData.address,
apartment : this.matchedData.address2,
stateZip : this.matchedData.zipcode
})
From then, I'm printing out all of these things in order that they're declared. However, some of the data doesn't have an apartment number so it'll show up as:
John Doe
6/6/2018
135 Testdemo Avenue
null
NY 11111
Is it possible to use an if function within declaring the consts in order to make it so that:
if (this.matchedData.address2 == null){
//Do nothing
} else {
apartment : this.matchedData.address2,
}
No, but you can use a ternary
var object = {
address: '1111',
apartment : this.matchedData.address2 ? "" : this.matchedData.address2
}
You could use Object.assign and check with property and if not null, take an object for assignment.
printBlock(Object.assign(
{
name: this.matchedData.clientName,
date: this.matchedData.jobDate,
destination: this.matchedData.address,
apartment: this.matchedData.address2,
stateZip: this.matchedData.zipcode
},
this.matchedData.address2 === null || { apartment: this.matchedData.address2 }
));
You can create your object first without the apartment entry and then add the apartment entry if it is not null...
const a = {
name : this.matchedData.clientName,
date : this.matchedData.jobDate,
destination : this.matchedData.address,
stateZip : this.matchedData.zipcode
};
if (this.matchedData.address2 !== null){
a.apartment : this.matchedData.address2;
}
const printBlock({...}) will throw an error because it isn't a valid way to initialize a constant. If printBlock is a function, why not handle null values in the body of printBlock?
function printBlock(obj) {
for (var prop in obj) {
if (obj[prop]) {
console.log(obj[prop]); // or do whatever you mean by 'print'
}
}
}
Related
In Angular 6 I try to get each object of an array and compare it to the objects of another array. If they match, remove the object from the second array.
Based on this, I have the following code :
existing.forEach((existingitem, existingindex, existingfeatures) => {
newdata2 = newdata.filter(item => (existingitem.values_.id != item.properties.id && existingitem.values_.cat != item.properties.cat));
});
So, if I had the existing like
var existing= [
{ name : "John", values_:{id:1, cat:true} },
{ name : "Alice", values_:{id:2, cat:false} }
];
and newdata
var newdata= [
{ name : "Mike", properties:{id:7, cat:true} },
{ name : "Jenny", properties:{id:2, cat:false} }
];
compare the properties of newdata to the values_ of existing and the ones not matching end up in newdata2 , so newdata2 now is
var newdata2= [
{ name : "Mike", properties:{id:7, cat:true} }
];
This may look simple, yet I get
ERROR TypeError: newdata_1.filter is not a function
referring to the line
newdata2 = newdata.filter(item => (existingitem.values_.id != item.properties.id && existingitem.values_.cat != item.properties.cat));
What am I missing here? Please advice.
Thanks
EDIT
I dont set any var as newdata_1 in my code, and all the values named newdata or newdata2 are in the same block of code. I am also confused about the newdata_1 name. If I change the name , for example newdatafeat, the error becomes ERROR TypeError: newdatafeat_1.filter is not a function . I have no clue.
Thanks
I think I ran into a wrong direction and now I'm really stucked. That's why I'm asking for your help.
Summary: I'm trying to switch between two possible input data of a function and I need to check for empty value, to get a valid result array. The array structure is fixed (I can't change that) and if any value is missing or the input object doesn't match (for example less elements then expected), the result should be data = false
There is a function with one parameter (template). But the input differs:
First of all,
I have to check if the data comes as an simple object into the function
like
template = { type: 'anything', 0: 'Book title', 1: 'Article title', 2: 'Name', 3: '1' }
or
if there is a ReactiveDict-variable (which I would access like this: template.dict.get('type')) from where the data has to be taken.
In the latter case the data is also stored in the variable template, but I have to change the access to it slightly: template.dict.get('type') vs. template.type
It could also be the case, that there is no (correct) data at all: For example no data or an object with less or more elements as expected.
So I tried to use this, to switch between both input types:
const type = template.type || template.dict.get('type')
This doesn't work as sometimes I get the error Cannot read property 'get' of undefined. I think if there is no input type at all, so template.type is undefined and there is no ReactiveDict, which means template.dict is undefined.
Second I need to check if all variables has values: Each (trimmed) value needs to be a string.
For future development I would like to verify the data of each variable (I think with regEx) to make this function a bit better. Example: edition should be a number (but stored as a string).
function
function(template) {
const type = template.type || template.dict.get('type'), // How to do this better?
docId = '12345';
let data = false;
if (type === 'anything') {
const title = template[0] || template.dic.get(0).value, // How to do those better?
article = template[1] || template.dic.get(1).value,
author = template[2] || template.dic.get(2).value,
edition = template[3] || template.dic.get(3).value;
if (title && article && author && edition) // How to check each value smarter?
data = [
[
{ title: title.trim() },
{ article: article.trim() },
{ author: author.trim() },
{ reference: docId }
],
{
title: title.trim(),
type : type
},
{
article: article.trim()
},
{
author : author.trim(),
edition : edition.trim()
},
{
reference: docId
}
];
}
return data;
}
Good morning,
replace
const type = template.type || template.dict.get('type')
by
const type = template.type || (template.dict && template.dict.get('type'))
I see you use es6 so you can do destructuring affectation:
const [title,author,article,author] = template
but after it don't solve the fact you have to check they are undefined or not, you can use an object instead
o = {}
var oneValueIsEmpty = false
["title","article","author","edtiton"].forEach(function(key,i){
o[key] = template[i] || template.dic.get(i).value
oneValueIsEmpty = oneValueIsEmpty || !o[key]
})
if (!oneValueIsEmpty )
data = [
[
{ title: o.title.trim() },
{ article: o.article.trim() },
{ author: o.author.trim() },
{ reference: docId }
],
{
title: o.title.trim(),
type : type
},
{
article: o.article.trim()
},
{
author : o.author.trim(),
edition : o.edition.trim()
},
{
reference: docId
}
];
You could
const type = template.type || template.dict.get('type')
change into
const type = template && template.dict
? template.dict.get('type')
: template.type;
and
const title = template && template.dict
? template.dict.get(0).value
: template[0];
Edit:
Also I would recommend explicitly writing const and let before each variable and not using comma to declare multiple variables. It always is a mess for next guy who has to maintain your code although this is very opinionated.
You're declaring:
const type = template.type || template.dict.get('type'),
But here you're referring to template.dic.get as opposed to dict, that won't help much.
if (type === 'anything') {
const title = template[0] || template.dic.get(0).value, // How to do those better?
article = template[1] || template.dic.get(1).value,
author = template[2] || template.dic.get(2).value,
edition = template[3] || template.dic.get(3).value;
you can use:
if (typeof template.dict !== 'undefined')
To check whether the object exists.
In my node (express) app, I want to send a json response back to the client.
It would look something like this.
{"someTshirt":
{small : 'available'},
{med : 'available'},
{large : 'not available'}
}
I'd reiterate through the sizes and append to the response set with its availability. How would I create this object to begin with in plain javascript within app.js? how would I add the 'someTshirtName' to the beginning of this object as well as appending each size's availability to it after the object has been created?
You can build your object like this:
var availability = {"someTshirt":
{
'small': 'available',
'med' : 'available',
'large' : 'not available'
}
};
Then you can access this object with:
availability.someTshirt.small
>>> 'available'
availability.someTshirt.large
>>> 'not available'
However I'd recommend you to use booleans instead of strings, which are easier to manipulate. You can still change the display string later:
var availability = {"someTshirt":
{
'small': true,
'med' : true,
'large' : false
}
};
if (availability.someTshirt.small) {
console.log('available');
}
>>> 'available'
[edit]
Response to the comment:
If you want to create your objects dynamically, you can do the following:
var availability = {};
availability.someTshirt = {};
availability.someTshirt.small = true;
availability.someTshirt.med = true;
availability.someTshirt.large = false;
if (availability.someTshirt.small) {
console.log("available");
} else {
console.log("not available");
}
>>> 'available'
availability.someTshirt.small = false;
if (availability.someTshirt.small) {
console.log("available");
} else {
console.log("not available");
}
>>> 'not available'
If you need to build your object based on JSON string returned to your code, you can use eval statement. for example you have a string variable sJsonResult containing your JSON response. Your code can go something like;
var sJsonResult = "{someTshirt: {small : 'available', med : 'available',large : 'not available'}}";
var o;
eval("o = " + sJsonResult);
alert(o.someTshirt.small);
I am looking to write a function which can look up a value based on a key and replace that value with another. The key is a tree from the start node of JSON. Here is the example.
var myData = {
name : 'Dan',
address: {
city : 'Santa Clara',
details : {
'prevhouse' : ''
}
}
}
Input to the function is a key tree. For eg, myData-address-details-prevhouse
When I pass this key with a new value, say 'Texas', the prevhouse value will get changed to the new value I am sending.
and new JSON will be
var myData = {
name : 'Dan',
address: {
city : 'Santa Clara',
details : {
'prevhouse' : 'Texas'
}
}
}
Here is what I wrote so far
var tree = key.split("-");
now the tree variable contains ["myData","address", "details","prevhouse"]
I know that we can access the object using myData[tree[0]][tree[1]][tree[2]], but somehow not able to get it dynamic from parsed value.
how do we generate this dynamically since the length of the depth is not known till runtime.
Hope to get a help.
try with this code:
var myData = {
name: 'Dan',
address: {
city: 'Santa Clara',
details: {
prevhouse: ''
}
}
};
function setAttribute(obj, key, value) {
var i = 1,
attrs = key.split('-'),
max = attrs.length - 1;
for (; i < max; i++) {
attr = attrs[i];
obj = obj[attr];
}
obj[attrs[max]] = value;
console.log('myData=', myData);
}
setAttribute(myData, "myData-address-details-prevhouse", "Texas");
here a working jsfiddle demo; see the console for the result
You should be able to iterate through each key because your JSON is just a JS object. So go through each key, check if it's defined, if it is, use that object for your next check. That'll get you where you want to go. Keep in mind you'll be setting the last key to your value.
basic psuedo-code without dealing with setting:
obj = data;
for (key in keys) {
obj = obj[key]
}
Something like this would do:
function update(node, path, value) {
path = path.split('-');
do {
node = node[path.splice(0, 1)];
} while(path.length > 1);
node[path[0]] = value;
}
Given that myData is the object, I think you should be using myData[tree[1]][tree[2]][tree[3]] and throwing away the first item in the array.
Something like this should work recursively (untested)
function updateValue(obj, key, value)
{
var keys = key.split('-');
updateObjectValue(obj, keys.shift(), value);
}
function updateObjectValue(obj, keyArray, value)
{
if (keyArray.length == 1) {
obj[keyArray[0]] = value;
}
else if (keyArray.length > 1) {
updateObject(obj[keyArray[0]], keyArray.shift(), value);
}
}
I'm trying to calculate all documents where a certain field exists (in this case it's "country" field) with Map+Reduce, and the only solution that worked for me is this:
mapper = Code("""
function () {
if (typeof this.country != 'undefined') {
var key = 1
emit(key, {count: 1})
};
};
""")
I'm not really interested in keys, just if field exists, so I just passed 1.
But I'm sure that's wrong.
reducer = Code("""
function (key, values) {
var sum = 0;
values.forEach(function (value) {
sum += value['count'];
});
return {count: sum};
};
""")
And then calling map_reduce:
results = dbHandle.cards.map_reduce(mapReduce.mapper, mapReduce.reducer, "resultsMR")
for doc in results.find():
print "Found %s documents." % int(doc.get('value').get('count'))
Also I'm thinking on how to get the amount of docs where their creation date is > than other date, should I use a "query" option in map_reduce function?
query = {"foundationDate":{"$gt":datetime.datetime(2012, 1, 1, 00, 00, 00)}}
Thank you :)
Per Chien-Wei Huang comment, why not use the in built functionality e.g.
db.somName.find({"country":{"$exists":True}}).count()
Else if you want some token map-reduce code you cold simply mimic the count functionality, via the group() function e.g.
db.somName.group(
{ cond: { "country" : {$exists : true} }
, key: { }
, initial: {count : 0}
, reduce: function(doc, out){ out.count++}
}
);
Note: If you also want a count by country value, then stick the following in the key:
, key { "country" : 1 }