How can I do more elegantly several _.has checks? - javascript

I have an object like this
myObject:{"property1": "valueX",
"property2": "valueY",
"property3": "valueZ",
"property4": "valueV",
"property5": "valueW"}
and I want to make sure that none of my object properties names match several strings.
The most intuitive way I found is this one:
if( !_.has(myObject, "TestingValue1")&&
!_.has(myObject, "TestingValue2")&&
!_.has(myObject, "TestingValue3")&&
!_.has(myObject, "TestingValue4")){
//do something
}
But if I have too much property names to check, it is becoming quite a large piece of code.
I am trying to come up with a more elegant solution. I feel it is almost ok but I does not appear to work (it always returns true). Here it is:
var TestingValues = ["TestingValue1", "TestingValue2", "TestingValue3"]
if (!_.every(TestingValues, _.partial(_.has, myObject))){
//do something
}
Can you tell me what is wrong? How should I declare TestingValues?
EDIT:
#Sergiu Paraschiv I used different values in myObject and the test array only for making it easier to read. Of course I tested it with identical values.
You are right, I just realized it works. I didn't at first because it does not work as intended. I mixed things up: I want to return false if any of the item in the string array matches any of the attributes of myObject

You can do :
var TestingValues = [ "TestingValue1", "TestingValue2", "TestingValue3" ];
if(!_.isEmpty(_(myObject).pick(TestingValues)){...
or as you suggested yourself :
if (!_.some(TestingValues, _.partial(_.has, myObject)))

Alternative:
_some(TestValues, function(test) { return _.indexOf(_.values(myObject), test) != -1});

You can try
var testingValues = ["TestingValue1", "TestingValue2", "TestingValue3"];
var myObj = {
"property1": "valueX",
"property2": "valueY",
"property3": "valueZ",
"property4": "valueV",
"property5": "valuez"
};
var result = _.every(myObj, function(value, key, obj){
return !_.contains(testingValues, value);
});
console.log(result);

Related

Naming a JSON array using Jquery

I have an array of JSON:
[{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225?v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/8931462?v=4","Name":"aws-microservices-deploy-options","Score":20.521696,"Updatedat":"2018-07-20T12:22:07Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/4046529?v=4","Name":"useful-jenkins-groovy-init-scripts","Score":21.447626,"Updatedat":"2018-07-18T19:52:02Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/6755615?v=4","Name":"dnsjava","Score":34.74705,"Updatedat":"2018-06-28T15:16:45Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/504773?v=4","Name":"luke","Score":19.239859,"Updatedat":"2018-06-28T07:27:26Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/536912?v=4","Name":"Wicket-tutorial-examples","Score":37.265644,"Updatedat":"2018-07-14T04:28:50Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/33330803?v=4","Name":"nexus-repository-apt","Score":44.401646,"Updatedat":"2018-07-06T18:28:13Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1321963?v=4","Name":"marc4j","Score":28.282797,"Updatedat":"2018-07-07T15:58:57Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/5622390?v=4","Name":"jamonapi","Score":24.564436,"Updatedat":"2018-07-16T07:44:35Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}]
I want it to be:
{
gitdList: [
{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225? v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},
{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}
]
}
I searched and am finding solutions regarding php only , to use json.encode.
How do I do it using JQUERY?
Have you try like this way? just create an empty object like this object = {} and assign your existing value i.e avatar_urls to it with your desired key i.e gitdList. Hope this will work for you.
var avatar_urls = [{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225?v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/8931462?v=4","Name":"aws-microservices-deploy-options","Score":20.521696,"Updatedat":"2018-07-20T12:22:07Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/4046529?v=4","Name":"useful-jenkins-groovy-init-scripts","Score":21.447626,"Updatedat":"2018-07-18T19:52:02Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/6755615?v=4","Name":"dnsjava","Score":34.74705,"Updatedat":"2018-06-28T15:16:45Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/504773?v=4","Name":"luke","Score":19.239859,"Updatedat":"2018-06-28T07:27:26Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/536912?v=4","Name":"Wicket-tutorial-examples","Score":37.265644,"Updatedat":"2018-07-14T04:28:50Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/33330803?v=4","Name":"nexus-repository-apt","Score":44.401646,"Updatedat":"2018-07-06T18:28:13Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1321963?v=4","Name":"marc4j","Score":28.282797,"Updatedat":"2018-07-07T15:58:57Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/5622390?v=4","Name":"jamonapi","Score":24.564436,"Updatedat":"2018-07-16T07:44:35Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}]
var object = {};
object.gitdList = avatar_urls;
console.log(object);
Edit: pretty neat and better way to do it.
var object = { gitdList: avatar_urls};
console.log(object);
maybe like this:
var data=[{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225?v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/8931462?v=4","Name":"aws-microservices-deploy-options","Score":20.521696,"Updatedat":"2018-07-20T12:22:07Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/4046529?v=4","Name":"useful-jenkins-groovy-init-scripts","Score":21.447626,"Updatedat":"2018-07-18T19:52:02Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/6755615?v=4","Name":"dnsjava","Score":34.74705,"Updatedat":"2018-06-28T15:16:45Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/504773?v=4","Name":"luke","Score":19.239859,"Updatedat":"2018-06-28T07:27:26Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/536912?v=4","Name":"Wicket-tutorial-examples","Score":37.265644,"Updatedat":"2018-07-14T04:28:50Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/33330803?v=4","Name":"nexus-repository-apt","Score":44.401646,"Updatedat":"2018-07-06T18:28:13Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1321963?v=4","Name":"marc4j","Score":28.282797,"Updatedat":"2018-07-07T15:58:57Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/5622390?v=4","Name":"jamonapi","Score":24.564436,"Updatedat":"2018-07-16T07:44:35Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}];
var new_data={ 'gitdList': data };
console.log(new_data);

set array as value in json format in Javascript

I want to add array as json value.
Json format is as follows.
json_data = [
'name':'Testing'
'email':'TestEmail'
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
]
How can I set value of 'links' in javascript like that?
I did as follows.
links_array = [];
links_array =['testing','test2'];
json_data.links = links_array;
I wanted to append these two string but couldn't.
Any help would be appreciate.
Assuming that the syntax of your example is correct, you can use the "push" method for arrays.
json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[]
};
json_data.links.push("test1#test.com");
json_data.links.push("test2#test.com");
json_data.links.push("test3#test.com");
You have to make little changes to make it work.
First thing, You have to replace initial square brackets with curly one. By doing this your object will become JSON Literal - a key value pair.
Second thing, You have missed commas after 'name':'Testing' and 'email':'TestEmail'
Below will work perfectly:
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
}
In addition to push as mentioned by #giovannilobitos you can use concat and do it all in one go.
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com'
]
};
var links_array = ['testing','test2'];
json_data.links = json_data.links.concat(links_array);
console.log(json_data.links);
On MDN's array reference you can find a more complete list of how to modify arrays in JavaScript.

Printing Information from JSON string

I have the following JSON string:
var txt=
{
"people":
[{
"person":
{
"firstname":"Jane",
"lastname":"Doe"
}
},
{
"person":
{
"firstname":"John",
"lastname":"Smith"
}
}
]
};
I want the program to alert that there are two people in the list, but when I do my count function, it only says 1 (gets to 'people' then doesn't go deeper into the list).
Here is the fiddle:
http://jsfiddle.net/LipeeVora/rsBYb/3/
You don't need a to write a counting loop. txt.people.length will give you the count, as txt.people is an array object.
See my revised fiddle for an example: http://jsfiddle.net/rsBYb/5/
Your loop was counting the elements in txt - of which there is only one (the people array). It would work fine if you instead use txt.people in the loop. You really want to count the elements in txt.people, not txt.
Example of this: http://jsfiddle.net/rsBYb/8/
txt.people.length
will give you the correct answer
http://jsfiddle.net/rsBYb/6/
It is because you count people and not persons.
Change your loop to this:
for ( property in txt.person )
{
count++;
}
alert("count = " + count);
This should work:
txt.people.length
You might have to do a JSON.parse depending on where you're pulling your JSON string from (if you're doing anything with it outside of the fiddle)

Add objects to JSON

I have a JSON that looks like this:
{
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
}
When I add an object to it:
addObj[obj.length] = saveobject;
the previous content gehts replaced.
When I make an array out of it and push the object:
addObj = [loadedJSON];
addObj.push(saveObj);
I get this after the first
[Object]
after the second so fare so good
[Object, Object]
and after the third it gets messed up
[Array(2), Object]
What do I miss?
I hope some one can help with this?
The way I hoped it would look like is this.
[Object, Object, Object, ...and so on]
EDIT
to be More specific
when I add a new Object I load the JSON file in a variable and then I try to add the new Object.
Which works for the first two objects but the third one is added to the first object so that I got this result.
[Array(2), Object]
I dont want it nested like this! But how do I get it like this?
[Object, Object, Object].
EDIT
So eventually you all were right I just mixed up the array when i loaded it the second time every thing is fine now thank for pointing me in the right direction.
on the first time:
var a= [];
var b= {};
b= 'some things';
a.push(b);
and wenn a.length != null
b= 'the rest';
a.push(b);
and now everything is just as expected!
As far as I understand it, this has nothing to do with JSON.
It seems you want to have an array storing successive instances of a given object (that happens to have been encoded in JSON at some point, but for the problem at hand we could not care less).
First, create a sorage array.
Then push each new instance into it.
var storage = []; // your storage array, initially empty
// ....
while (some_guy_wants_to_send_me_something ())
{
var new_object = get_what_the_guy_sent_me_that_happens_to_be_JSON_encoded();
storage.push (new_object);
}
EDIT:
If you use a button:
var storage = []; // your storage array, initially empty
// ....
function add_whatever_object ()
{
var new_object = get_what_the_guy_sent_me_that_happens_to_be_JSON_encoded();
storage.push (new_object);
}
// HTML
<button type="button" onclick='add_whatever_object();'>
I still don't see where the catch is.
check the if it is an array:
Array.isArray(loadedJSON) //true
do this:
loadedJSON.push(saveObj);
if it was not an array push it to an array:
var myarray = [];
myarray.push(loadedJSON);
an then push your other object:
myarray.push(saveObj);
an so on:
myarray.push(otherObj);
I am a little unclear on what you actually want, but based on a little speculation I was able to write the following code for you. I hope this will solve your problem.
var a ={
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
};
var b ={
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
};
var c ={
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
};
var ObjArr = [];
ObjArr.push(a);
ObjArr.push(b);
ObjArr.push(c);
console.log(ObjArr);
Here is the fiddle to it => http://jsfiddle.net/rB3Un/

Add additional object to variable in javascript?

I have a variable that may contain objects or may be undefined. I wish to add additional objects to this variable. How do I do that?
code example when applicable:
function(){
var comments;
if(fbposts[fbpost].comments.count){
for(var comment in fbposts[fbpost].comments.data){
comments = ({
name: fbposts[fbpost].comments.data[comment].from.name,
link: "http://www.facebook.com/"+fbposts[fbpost].comments.data[comment].from.id,
img: "http://www.facebook.com/"+fbposts[fbpost].comments.data[comment].from.id+"/picture",
message: fbposts[fbpost].comments.data[comment].message,
created: timeDifference(Date.parse(fbposts[fbpost].comments.data[comment].created_time)),
})
}
}
return comments;}(),
Test if it is undefined and if so assign it to an empty object:
if (typeof yourVar === "undefined")
yourVar = {};
yourVar.additionalObject1 = { something : "test" };
yourVar.additionalObject2 = { something : "else" };
EDIT: OK, now that you've added code to your question, it seems like your comments variable should be an array, since you are adding to it in a loop. So I think you'd want to do something like this:
(function(){
var comments = [];
if(fbposts[fbpost].comments.count){
for(var comment in fbposts[fbpost].comments.data){
comments.push({
name: fbposts[fbpost].comments.data[comment].from.name,
link: "http://www.facebook.com/"+fbposts[fbpost].comments.data[comment].from.id,
img: "http://www.facebook.com/"+fbposts[fbpost].comments.data[comment].from.id+"/picture",
message: fbposts[fbpost].comments.data[comment].message,
created: timeDifference(Date.parse(fbposts[fbpost].comments.data[comment].created_time)),
});
}
}
return comments;
})();
comments will thus contain one element for each comment in your source data. If there are no comments it will be an empty array. (If you want it to return undefined if there are no comments then leave the variable declaration where it is as var comments and add comments=[]; just inside the if statement.)
If you're using jQuery (and why wouldn't you be?), then you want to look at $.extend()
http://api.jquery.com/jQuery.extend/

Categories

Resources