make the query dynamically to change using sanity.io groq - javascript

Hi there I'm trying to make a post request where I want to update one field on sanity.io
this is my query
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
`rewardItem[_key == \"${key}\"].lastTimeReward`: "TEst",
},
}
but this won't let me even run my project,
its giving me this error on console.log: Unexpected token;
When I do my query like this, it works
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
"rewardItem[_key == \"e88959e43ce7\"].lastTimeReward": "Test",
},
}
}]
Thanks a lot.

Your set-property is an object, and you can't enter a dynamic key directly into the object. To do what you are trying to do here, you can wrap the dynamic key in square brackets like this. That should give you the output you desire
const variable = "example"
const a = { [`template ${variable}`]: "value" }
console.log(a)

Related

assign variable to value of Dictionary Javascript

I am building a dictionary but I would like some of the values to contain variables. is there a way to pass a variable to the dictionary so I can assign a dot notation variable? the variables object will always have the same structure and the dictionary will be static and structured the same for each key value pair. essentially I want to pass the value from the dictionary to another function to handle the data.
main.js
import myDictionary from "myDictionary.js"
const variables ={
item:"Hello"
}
const data = myDictionary[key](variables)
console.log(data)
myDictionary.js
const myDictionary = {
key: variables.item
}
so the log should display hello. I know it willl be something straightforward but cant seem to figure it out.
as always any help is greatly appreciated
You should modify the dictionary so that it keeps actual callback functions instead. Only then it will be able to accept arguments.
const myDictionary = {
key: (variables) => variables.item
}
const variables = {
item: "Hello"
}
const key = "key";
const data = myDictionary[key](variables)
console.log(data)
What you are trying to do is not possible. The myDictionary.js file has no idea whats inside you main file. The only thing you could do would be:
myDictionary.js
const myDictionary = {
key: "item"
}
main.js
import myDictionary from "myDictionary.js";
const variables = {
item: "Hello"
};
const data = variables[myDictionary["key"]];
console.log(data);
Also, even though JavaScript does not enforce semi-colons, they will save you a lot of headaches of some stupid rule that breaks the automatic inserter.
I must apologise as when I asked the question I wasn't fully clear on what I needed but after some experimentation and looking at my edge cases and after looking at Krzysztof's answer I had a thought and came up with something similar to this -
const dict = {
key: (eventData) => {
return [
{
module: 'company',
entity: 'placement',
variables: {
placement_id: {
value: eventData.id,
},
},
},
{
module: 'company',
entity: 'placement',
variables: {
client_id: {
value: eventData.client.id,
},
},
},
];
},
}
Then I'm getting the data like this -
const data = dict?.[key](eventData)
console.log(data)
I can then navigate or manipulate the data however I need.
thank you everyone who spent time to help me

Filter Array Using Partial String Match in Javascript

I have an array of objects where the value I need to filter on is buried in a long string. Array looks like:
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
},
So if I wanted to grab all the partnerId objects where value includes parent_sku how would I do that?
console.log(data.value.includes('parent_sku') returns cannot read property 'includes' of null.
EDIT:
Didn't think this mattered, but judging by responses, seems it does. Here's the full response object:
Response body: {
"data": {
"configurationByCode": [
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
}
I'm passing that into a re-usable function for filtering arrays:
const parentSkuPartners = filterArray(res.body.data.configurationByCode, 'parent_sku');
Function:
function filterArray(array, filterList) {
const newList = [];
for (let i = 0; i < array.length; i += 1) {
console.log('LOG', array[i].data.value.includes('parent_sku');
}
}
The problem is somewhere else. The code you've tried should work to find if a value contains a string – I've added it the snippet below and you'll see it works.
The issue is how you are accessing data and data.value. The error message clearly states that it believes that data.value is null. We would need to see the code around it to be able to figure out what the problem is. Try just logging to console the value of data before you run the includes function.
const data = {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}", "partnerId": 1
};
console.log('includes?', data.value.includes('parent_sku'));
You can use data.value.includes('parent_sku') as you have suggested. The issue here is that your object is nested inside an unnamed object.
try:
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
The problem was some of the values for value were null. Adding an extra conditional fixed it:
if (array[i].data.value !== null) {
Use lodash includes, and lodash filter like
let configurationByCode = [{
data: {
value: {
cols:["parent_sku"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 1
}
}, {
data: {
value: {
cols:["nothing"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 2
}
}];
let wantedData = _.filter(configurationByCode, (config) => {
return _.includes(config.data.value.cols, 'parent_sku');
});
console.log( wantedData );
https://jsfiddle.net/76cndsp2/

Extracting values from multiple scope inside an array

I'm building a twitter bot that takes input of someone that DM's my account, and then will output the received DM's into tweet. I'm using twit package from npm. The question is, how do you extract the id's from the output, and then use the id's in another function in order to post the tweet, using? (note that I'm currently using console.log as the tweet for now).
Input command to check the direct messages
var listMsg = T.get('direct_messages/events/list', {
count: '50'
}, function(data, response) {
console.log(response)
Output in terminal (the multiple scope inside the events array)
{
events: [
{
type: 'message_create',
id: '1275746339314216965', //take this
created_timestamp: '1592996604170',
message_create: [Object]
},
{
type: 'message_create',
id: '1274664227584671750', //and this
created_timestamp: '1592738608629',
message_create: [Object]
}
]
}
Getting the content of a direct message
var getMsg = T.get('direct_messages/events/show', {
id:'1274664227584671750' //put it to this
}, function(data, response) {
//console.log(response)
let dm = response.event.message_create.message_data
console.log(dm) //and print the message here
The content of the direct message
{
text: 'Abcd',
entities: { hashtags: [], symbols: [], user_mentions: [], urls: [] }
}
I want to get the id's as a let just like in the third code block.
You can simply use the map array function to transform the object like this
events.map( function(e) { return e.id}) or you can use es6 syntax events.map(e=> e.id)
both would return an array like this
["1275746339314216965", "1274664227584671750"]
These could be joined into into a string like so
events.map(e=> e.id).join(",")
returning
"1275746339314216965,1274664227584671750"
map() is a great function try playing around with map reduce and filter to really improve your programming. There's a great article on them here https://medium.com/poka-techblog/simplify-your-javascript-use-map-reduce-and-filter-bd02c593cc2d
Of course you could do also use a good old fashioned for loop, but think that would be a bit verbose and unnecessary (the software equivalent of making your own hammer)
e.g.
var ids = []
for(var event of events) {
ids.push(event.id)
}

Map the values in object with the given value in react

I am new to the react, Here I have one array of object which is like
const bgStatus =
[{
Id: "809"
Name: "PRE"
Description: "PRE"
Value: "VP:PRE"
},
{
Id: "809"
Name: "CLO"
Description: "CLO"
Value: "VP:CLO"
},
{
Id: "809"
Name: "BU"
Description: "BU"
Value: "VP:BU"
}
]
Now , In this I have one method through which I get the value which is VP:PRE or VP:BU or VP:CLO
Now, I have the following function
getmsg = (bgSt, tobeChange, current) => {
return `Are you sure you want to change to ${tobeChange}? not possible to go ${current} `
}
Now, In this both the status tobeChange and current comes in a VP:PRE in this format. Now, I want to use the Description from that array for that value like for VP:PRE , it should be 'PRE' in the return value. Now ,
I have one solution which is like creating a key value map and then map it. But, I can not hard code that values over here.
So, and also don't want to use the includes or contains things.
Result which I want - When I am calling the function
getmsg this time in params I am passing , tobeChange is `"VP:PRE"`, current is "VP_BU" and bgStatus is the array of object.
Now in return I should get this message ,
`Are you sure you want to change to PRE not possible to go BU `
The values VP_PRE should get replaced with the description PRE
Well if you are always getting the two variables :
tobeChange=VP:something_to_change
current=VP:something
It has nothing to do with react it is javascript traitement
I suggest you use the function split here is an example :
getmsg = (tobeChange, current) => {
toChange=tobeChange.split(":")
tobeChange=toChange[1]
curr=current.split(":")
current=curr[1]
return `Are you sure you want to change to ${tobeChange}? not possible to go ${current} `
}
tobeChange="VP:something_to_change"
current="VP:something_current"
console.log(getmsg(tobeChange, current))

How to make a JSON object?

I want to create the following JSON object, as seen from a console log:
Object
. member: Object
. id: 8286
I've been trying:
'member' :[{'id': 8286}]
but get the following error: "Uncaught SyntaxError: Unexpected token :"
What am I doing wrong? Thanks
var member = {
id: 8286
};
this allows you to access it like
member.id
You could have also meant something like:
var data = {
member: {
id: 8286
}
};
which you would access like so:
data.member.id
If this is not what you want, please clarify in your post cause I'm not sure I'm following your request correctly.
You're missing the curly braces surrounding the object.
As in:
var x = {'member': [{'id':8286}]};
You mean something like this?
{
"member": {},
"id": 8286
}
{
"member":{
"id":value
},
{
another_data:value
}
}
the data are accesses using the(.) operator.
the id is accessed by member.id

Categories

Resources