change value in a object,Object - javascript

How do i change a value in a variable ?
var elementorFrontendConfig = {
"environmentMode": {
"edit": false,
"wpPreview": false
},
"is_rtl": false,
"breakpoints": {
"xs": 0,
"sm": 480,
"md": 768,
"lg": 1025,
"xl": 1440,
"xxl": 1600
},
"version": "2.8.5",
"urls": {
"assets": "http:\/\/wptheme.tst\/wp-content\/plugins\/elementor\/assets\/"
},
"settings": {
"page": [],
"general": {
"elementor_global_image_lightbox": "yes"
},
"editorPreferences": []
},
"post": {
"id": 6007,
"title": "Elementor #6007",
"excerpt": ""
},
"user": {
"roles": ["administrator"]
}
};
This does not work
elementorFrontendConfig['settings']['general']['elementor_global_image_lightbox']= 'no';

The JS code is okay and does work. It might not be called, depending on where your <script> tag has been placed in the code.

this works
check the fiddle, may be there is something else wrong with your environment
var elementorFrontendConfig = {"environmentMode":{"edit":false,"wpPreview":false},"is_rtl":false,"breakpoints":{"xs":0,"sm":480,"md":768,"lg":1025,"xl":1440,"xxl":1600},"version":"2.8.5","urls":{"assets":"http:\/\/wptheme.tst\/wp-content\/plugins\/elementor\/assets\/"},"settings":{"page":[],"general":{"elementor_global_image_lightbox":"yes"},"editorPreferences":[]},"post":{"id":6007,"title":"Elementor #6007","excerpt":""},"user":{"roles":["administrator"]}};
elementorFrontendConfig['settings']['general']['elementor_global_image_lightbox']= 'no';
alert(elementorFrontendConfig['settings']['general']['elementor_global_image_lightbox']);
https://jsfiddle.net/pj704k3u/

Related

How to update value X?

I want to use immutability-helper to update the object contained in my variable, the variable contains the following..
{
"_id": "XXXXX",
"_rev": "XXXXX",
"keys": {
"component": "TEST",
"type": "system"
},
"content": {
"services": {
"event": {
"url": "https://example.net"
},
"copy": {
"url": "https://example.net"
},
"humley": {
"url": "https://example.net",
"credentials": {
"user": "TEST",
"password": "TEST"
}
}
},
"settings": {
"processing": false,
"syncTimeout": {
"interval": 1,
"intervalUnit": "minutes"
},
"products": {
"hum": {
"copySyncDate": "2017-01-21T13:20:12.633Z",
"eventSyncDate": "",
"workspaceSyncDate": ""
}
}
},
"syncTimeout": {
"interval": 1,
"intervalUnit": "minutes"
}
}
}
I am looking to update the values
"hum": {
"copySyncDate": "2017-01-21T13:20:12.633Z",
"eventSyncDate": "",
"workspaceSyncDate": ""
I believe I can use the update function to update and store the new data in a new variable -
const documentUpdate = update(document, XXX);
But I can't work out what XXX needs to be, hope someone can help..
Thanks
You can do something like this:
const documentUpdate = update(
document,
{
content: {
settings: {
products: {
hum: {
$merge: {
copySyncDate: 'value',
}
}
}
}
}
},
)
You could use $set instead of $merge if you want to replace the entire block.

New to node.js here. How do I properly get the JSON from the top of a subreddit?

I am trying to call a get on this api url here: http://www.reddit.com/r/reddevils/top.json?sort=top&t=day&limit=1
and all I am trying to do is grab the permalink data, which is an element inside of an object called 'data' which is nested in another object called 'data'. I need the permalink data, so, I can export it and use it in another file.
I am trying to do this on node.js, how would I go about doing this? I have attempted to use the http, express, and ajax-request packages. I feel like I am on the right path, but it may be just a matter of proper syntax.
This is what I have right now. I was just trying to print out the JSON object onto my console to see if I am on the right path:
var request = require('ajax-request');
var http = require('http');
var url = "http://www.reddit.com/r/reddevils/top.json?sort=top&t=day&limit=1";
http.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var redditResponse = JSON.parse(body);
console.log("Got a response: ", redditResponse.picture);
});
}).on('error', function(e){
console.log("Got an error: ", e);
});
Thanks
When formatted, your data looks like this:
{
"kind": "Listing",
"data": {
"modhash": "fop7jgfq8z07efe8b23281496fdcd30eae5038b50d6b9811d2",
"children": [{
"kind": "t3",
"data": {
"contest_mode": false,
"subreddit_name_prefixed": "r/reddevils",
"banned_by": null,
"media_embed": {},
"thumbnail_width": 140,
"subreddit": "reddevils",
"selftext_html": null,
"selftext": "",
"likes": null,
"suggested_sort": null,
"user_reports": [],
"secure_media": null,
"link_flair_text": "TIER 0",
"id": "6jqxwx",
"view_count": null,
"secure_media_embed": {},
"clicked": false,
"report_reasons": null,
"author": "SuperShadowJr",
"saved": false,
"mod_reports": [],
"name": "t3_6jqxwx",
"score": 792,
"approved_by": null,
"over_18": false,
"domain": "instagram.com",
"hidden": false,
"preview": {
"images": [{
"source": {
"url": "https://i.redditmedia.com/qKDgoT2EDbwYbozYQO23nDisAj6yd9I2XwdWKLw-QNQ.jpg?s=5fe73832273b3e88324a6da17fa55fae",
"width": 640,
"height": 640
},
"resolutions": [{
"url": "https://i.redditmedia.com/qKDgoT2EDbwYbozYQO23nDisAj6yd9I2XwdWKLw-QNQ.jpg?fit=crop&crop=faces%2Centropy&arh=2&w=108&s=b668298ccd3a69304ab23c5aef1b6d77",
"width": 108,
"height": 108
}, {
"url": "https://i.redditmedia.com/qKDgoT2EDbwYbozYQO23nDisAj6yd9I2XwdWKLw-QNQ.jpg?fit=crop&crop=faces%2Centropy&arh=2&w=216&s=706a70a275e20973e8ce772f362db87f",
"width": 216,
"height": 216
}, {
"url": "https://i.redditmedia.com/qKDgoT2EDbwYbozYQO23nDisAj6yd9I2XwdWKLw-QNQ.jpg?fit=crop&crop=faces%2Centropy&arh=2&w=320&s=42c33880cf1a0a1c14e814de5469a1a1",
"width": 320,
"height": 320
}, {
"url": "https://i.redditmedia.com/qKDgoT2EDbwYbozYQO23nDisAj6yd9I2XwdWKLw-QNQ.jpg?fit=crop&crop=faces%2Centropy&arh=2&w=640&s=783b2011d7523d9c84450293eef9d6c0",
"width": 640,
"height": 640
}],
"variants": {},
"id": "TNO0lZhaqwUX-vbTYG6y0bI6hZhhgQJWTgm_OVk7b2E"
}],
"enabled": false
},
"thumbnail": "https://a.thumbs.redditmedia.com/8U2J6sELZ1AIGDsReUz-v10X3qyFG49TBH0XrjXAMc8.jpg",
"subreddit_id": "t5_2rxse",
"edited": false,
"link_flair_css_class": "black",
"author_flair_css_class": null,
"gilded": 0,
"downs": 0,
"brand_safe": true,
"archived": false,
"removal_reason": null,
"post_hint": "link",
"can_gild": true,
"thumbnail_height": 140,
"hide_score": false,
"spoiler": false,
"permalink": "/r/reddevils/comments/6jqxwx/fabinhos_girlfriendwife_likes_ig_picture_of/",
"num_reports": null,
"locked": false,
"stickied": false,
"created": 1498574067.0,
"url": "https://www.instagram.com/p/BV0dLySgy82/",
"author_flair_text": null,
"quarantine": false,
"title": "Fabinho's girlfriend/wife likes IG picture of Fabinho in MUFC kit with the caption \"Could we see this man in the PL?\"",
"created_utc": 1498545267.0,
"distinguished": null,
"media": null,
"num_comments": 79,
"is_self": false,
"visited": false,
"subreddit_type": "public",
"is_video": false,
"ups": 792
}
}],
"after": "t3_6jqxwx",
"before": null
}
}
So, you can use:
redditResponse.data.children[0].data.permalink
Working demo: https://jsfiddle.net/jfriend00/nkpchrk0/
If you want all the children, then you need to iterate i in:
redditResponse.data.children[i].data.permalink
to fetch each one.
Or, to get them all at once into their own array, you could do this:
let permaLinks = redditResponse.data.children.map(function(child) {
return child.data.permalink;
});

How to insert values of matching JSON Keys between 2 JSON files

I have 2 JSON files:
A Template JSON
A JSON output (from awscli)
The template is a small JSON file as below:
{
"DryRun": true,
"ImageId": "",
"KeyName": "",
"SecurityGroups": [
""
],
"InstanceType": "",
"Monitoring": {
"Enabled": false
},
"SubnetId": "",
"DisableApiTermination": true,
"PrivateIpAddress": "",
"IamInstanceProfile": {
"Arn": "",
"Name": ""
},
"EbsOptimized": true,
"TagSpecifications": [{
"ResourceType": "",
"Tags": [{
"Key": "",
"Value": ""
}]
}]
}
The original file is the output of aws ec2 describe-instances:
{
"Reservations": [{
"OwnerId": "123456789012",
"ReservationId": "r-12345678",
"Groups": [],
"Instances": [{
"Monitoring": {
"State": "disabled"
},
"PublicDnsName": "ec2-12-34-56-78.ap-southeast-1.compute.amazonaws.com",
"RootDeviceType": "ebs",
"State": {
"Code": 16,
"Name": "running"
},
"EbsOptimized": false,
"LaunchTime": "2016-02-09T03:06:21.000Z",
"PublicIpAddress": "12.34.56.78",
"PrivateIpAddress": "172.31.1.2",
"ProductCodes": [],
"VpcId": "vpc-1a2b3c4d",
"StateTransitionReason": "",
"InstanceId": "i-abcd1234",
"ImageId": "ami-1234abcd",
"PrivateDnsName": "ip-172-31-1-2.ap-southeast-1.compute.internal",
"KeyName": "tempKey",
"SecurityGroups": [{
"GroupName": "somegroup1",
"GroupId": "sg-ZZZZZ"
},
{
"GroupName": "somegroup2",
"GroupId": "sg-YYYYY"
}
],
"ClientToken": "NutKc123456789012",
"SubnetId": "subnet-00001234",
"InstanceType": "t2.medium",
"NetworkInterfaces": [{
"Status": "in-use",
"MacAddress": "02:AA:BB:CC:DD:EE",
"SourceDestCheck": true,
"VpcId": "vpc-1a2b3c4d",
"Description": "",
"Association": {
"PublicIp": "12.34.56.78",
"PublicDnsName": "ec2-12-34-56-78.ap-southeast-1.compute.amazonaws.com",
"IpOwnerId": "123456789012"
},
"NetworkInterfaceId": "eni-XXXXXXXX",
"PrivateIpAddresses": [{
"PrivateDnsName": "ip-172-31-1-2.ap-southeast-1.compute.internal",
"Association": {
"PublicIp": "1.2.3.4",
"PublicDnsName": "ec2-12-34-56-78.ap-southeast-1.compute.amazonaws.com",
"IpOwnerId": "123456789012"
},
"Primary": true,
"PrivateIpAddress": "172.31.1.2"
}],
"PrivateDnsName": "ip-172-31-1-2.ap-southeast-1.compute.internal",
"Attachment": {
"Status": "attached",
"DeviceIndex": 0,
"DeleteOnTermination": true,
"AttachmentId": "eni-attach-XXXXXXXX",
"AttachTime": "2016-01-13T08:33:37.000Z"
},
"Groups": [{
"GroupName": "somegroup1",
"GroupId": "sg-ZZZZZZ"
},
{
"GroupName": "somegroup2",
"GroupId": "sg-YYYYYY"
}
],
"Ipv6Addresses": [],
"SubnetId": "subnet-00001234",
"OwnerId": "123456789012",
"PrivateIpAddress": "172.31.1.2"
}],
"SourceDestCheck": true,
"Placement": {
"Tenancy": "default",
"GroupName": "",
"AvailabilityZone": "ap-southeast-1b"
},
"Hypervisor": "xen",
"BlockDeviceMappings": [{
"DeviceName": "/dev/xvda",
"Ebs": {
"Status": "attached",
"DeleteOnTermination": true,
"VolumeId": "vol-33221100",
"AttachTime": "2016-01-13T08:33:39.000Z"
}
}],
"Architecture": "x86_64",
"StateReason": {
"Message": "Client.UserInitiatedShutdown: User initiated shutdown",
"Code": "Client.UserInitiatedShutdown"
},
"RootDeviceName": "/dev/xvda",
"VirtualizationType": "hvm",
"Tags": [{
"Value": "SomeValue",
"Key": "SomeKey"
},
{
"Value": "AnotherValue",
"Key": "Name"
}
],
"AmiLaunchIndex": 0
}]
}]
}
I want to copy the values of the Keys in the original JSON file to the template file.
For example, KeyName is a common key between the 2 JSON files. The corresponding value tempKey is replaced in the template file.
The main use case of this is: I am trying to migrate a number of servers on AWS from 1 region to another. This is a part of migration process which will remove tons of manual clicking and configuration on AWS Console.
Note: I use BASH command line.
There's a way to do this with jq but it doesn't take a JSON template as input.
You'll have to modify it to become a query. This isn't the actual query you need, but something to get you started:
cat temp.json | jq '.Reservations[].Instances[] | { DryRun, ImageId, KeyName, SecurityGroups, InstanceType, Monitoring }'
Where temp.json is your output above that I placed into a file. For regular commands, just do something like aws ec2 describe-instances | jq ...
The output that gives me (keep in mind the restricted set I queried for) is:
{
"DryRun": null,
"ImageId": "ami-1234abcd",
"KeyName": "tempKey",
"SecurityGroups": [
{
"GroupName": "somegroup1",
"GroupId": "sg-ZZZZZ"
},
{
"GroupName": "somegroup2",
"GroupId": "sg-YYYYY"
}
],
"InstanceType": "t2.medium",
"Monitoring": {
"State": "disabled"
}
}
Hope this helps.

Backbone - Collection not populating from JSON

I'm trying to populate a Backbone collection from the JSON that spotify API return me. However, after I try populating the collection I'm getting this with a console.log() :
playlistSpotify child {length: 1, models: Array[1], _byId: Object}. But my collection should contain 3 objects (3 objects in the JSON returned).
Any ideas of what's going on?
JS:
Model :
module.exports = Backbone.Model.extend({
defaults: {
id: null,
selected : false,
name: null
},
initialize: function() {
}
});
Collection :
module.exports = Backbone.Collection.extend({
model : Playlist,
initialize: function() {
}
});
View (Just the function that load the JSON):
loadSpotifyPlaylists : function() {
var that = this;
$.ajax({
url: 'https://api.spotify.com/v1/users/'+ this.user.get('spotifyId') +'/playlists',
headers: {
'Authorization': 'Bearer ' + this.user.get('spotifyToken')
},
success: function(response) {
var playlistCollection = new Playlists2({ collection : JSON.stringify(response.items) });
var playlistView = new PlaylistSpotifyView({ collection : playlistCollection });
that.$playListsSpotify.append(playlistView.render().el);
}
});
},
The JSON Spotify return me (I volontary remove one item to make it shorter) :
{
"href": "https://api.spotify.com/v1/users/loco/playlists?offset=0&limit=20",
"items": [
{
"collaborative": false,
"external_urls": {
"spotify": "http://open.spotify.com/user/loco/playlist/6MpEay73SWJzyJHGu5u6bK"
},
"href": "https://api.spotify.com/v1/users/loco/playlists/6MpEay73SWJzyJHGu5u6bK",
"id": "6MpEay73SWJzyJHGu5u6bK",
"images": [
{
"height": 640,
"url": "https://mosaic.scdn.co/640/dc8743ffb149138cfe29334147b835532dbee0ddf3320826…dc7e917657c7982eab6ed5126307c6c3a67e1a3fb78245a8477312eeaec1621a2849969219",
"width": 640
},
{
"height": 300,
"url": "https://mosaic.scdn.co/300/dc8743ffb149138cfe29334147b835532dbee0ddf3320826…dc7e917657c7982eab6ed5126307c6c3a67e1a3fb78245a8477312eeaec1621a2849969219",
"width": 300
},
{
"height": 60,
"url": "https://mosaic.scdn.co/60/dc8743ffb149138cfe29334147b835532dbee0ddf33208261…dc7e917657c7982eab6ed5126307c6c3a67e1a3fb78245a8477312eeaec1621a2849969219",
"width": 60
}
],
"name": "quizz musical",
"owner": {
"external_urls": {
"spotify": "http://open.spotify.com/user/loco"
},
"href": "https://api.spotify.com/v1/users/loco",
"id": "loco",
"type": "user",
"uri": "spotify:user:loco"
},
"public": false,
"snapshot_id": "1OUgCAhN+ZsJo6whDez1kVA/R2DooVY4Rzw+Vij5HYHgz/PDFpjbUaiXz+fkapX7",
"tracks": {
"href": "https://api.spotify.com/v1/users/loco/playlists/6MpEay73SWJzyJHGu5u6bK/tracks",
"total": 64
},
"type": "playlist",
"uri": "spotify:user:loco:playlist:6MpEay73SWJzyJHGu5u6bK"
},
{
"collaborative": false,
"external_urls": {
"spotify": "http://open.spotify.com/user/loco/playlist/2KlAANyACpjJZmZfVGK0Mb"
},
"href": "https://api.spotify.com/v1/users/loco/playlists/2KlAANyACpjJZmZfVGK0Mb",
"id": "2KlAANyACpjJZmZfVGK0Mb",
"images": [
{
"height": 640,
"url": "https://i.scdn.co/image/24e6e9aac4ea49d92e260bb6875f4882c65c7f48",
"width": 640
}
],
"name": "Playlist2",
"owner": {
"external_urls": {
"spotify": "http://open.spotify.com/user/loco"
},
"href": "https://api.spotify.com/v1/users/loco",
"id": "loco",
"type": "user",
"uri": "spotify:user:loco"
},
"public": true,
"snapshot_id": "fqLltawhg+mMNV+nVEl5Rmj94uDI1kdbbzoZLPbs7uVtZclbYJqyEtIAvIacExVe",
"tracks": {
"href": "https://api.spotify.com/v1/users/loco/playlists/2KlAANyACpjJZmZfVGK0Mb/tracks",
"total": 1
},
"type": "playlist",
"uri": "spotify:user:loco:playlist:2KlAANyACpjJZmZfVGK0Mb"
}
],
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total": 3
}
After some exploration I see this thing when I console.log the collection. I can't really understand what's happened.
Any help would be appreciated ! :)
You have a wrong creation of the instances. Change it to the next:
var playlistCollection = new Playlists2(response.items);
var playlistView = new PlaylistSpotifyView({ model : playlistCollection });
To initialize collection, you need just simply pass an array of objects as the argument to the constructor of collection

Display data from common topic in Freebase using jQuery

I am playing around with Freebase and have had some decent success, but have hit a wall. My MQL is below. I do not have any issue displaying name,latin name, etc, which I created in my base. I do not know how to display the article which is in a different base.
Here is the jQuery I am using to display data:
$('<div>',{text:this.name}).appendTo(document.body);
Thank you very much,
Todd
query : [
{
"/common/topic/article": {
"guid": null,
"limit": 1,
"optional": true
},
"/common/topic/image": {
"id": null,
"limit": 1,
"optional": true
},
"id": null,
"larval_food": [
{
"index": null,
"lang": "/lang/en",
"limit": 6,
"optional": true,
"sort": "index",
"type": "/type/text",
"value": null
}
],
"latin_name": [
{
"index": null,
"lang": "/lang/en",
"limit": 6,
"optional": true,
"sort": "index",
"type": "/type/text",
"value": null
}
],
"limit": 60,
"name": null,
"s0:type": [
{
"id": "/base/butterflies/butterfly",
"link": [
{
"timestamp": [
{
"optional": true,
"type": "/type/datetime",
"value": null
}
],
"type": "/type/link"
}
],
"type": "/type/type"
}
],
"sort": "-s0:type.link.timestamp.value",
"type": "/base/butterflies/butterfly"
}
]
Change
"type": "/base/butterflies/butterfly"
to the type of the thing you actually want to include.
As an aside, that looks like a query which was exported from one of the Freebase.com view pages. It can be greatly simplified and some of the stuff, like the sorting, you probably want removed altogether.
Here's your query simplied (I also recommend using the standard scientific name property instead of inventing your own "Latin name" property):
[{
"type": "/base/butterflies/butterfly",
"mid": null,
"name": null,
"/common/topic/article": [],
"/common/topic/image": ["mid":null,"optional":true],
"larval_food": [],
"latin_name": [],
"/biology/organism_classification/scientific_name" : [],
}]
Here's a version of the query which shows all organism classifications (species in this case) which have the tribe Danaini two levels up. It optionally decorates it with data (larval_food) from your base, if it exists:
[{
"type": "/biology/organism_classification",
"higher_classification": [{
"/biology/organism_classification/higher_classification": "Danaini"
}],
"mid": null,
"name": null,
"scientific_name": [],
"/common/topic/article": [],
"/common/topic/image": [{
"mid": null,
"optional": true
}],
"/base/butterflies/butterfly/larval_food": [],
}]
You can try it here: http://tinyurl.com/6wht7lx

Categories

Resources