Change JSON key and don't lose any data - javascript

I want to change json key but I can not manage
I tried to write a function:
modifySlotKey(requestObjectIntent, slotValue) {
requestObjectIntent['slots']['toChange'] = requestObjectIntent['slots'][slotValue]
return requestObjectIntent;
}
but it doesn't work.
My json is like that:
"slots": {
"toChange": {
"name": "query",
"value": "torte",
"confirmationStatus": "NONE",
"source": "USER"
}
}
but I want to change it to:
"slots": {
"slotValue": {
"name": "query",
"value": "torte",
"confirmationStatus": "NONE",
"source": "USER"
}
}
Could somebody help me please to solve this issue?

your code is fine but you only need to change the order of variables(slotValue = 'toChange') and delete de older key before return.
requestObjectIntent['slots'][slotValue] = requestObjectIntent['slots']['toChange];
delete(requestObjectIntent['slots']['toChange']);
I do a little example and works fine: https://jsfiddle.net/g7t4Lan5/1/

Related

Matching Object with 2 arrays with same key but different values from JSON API and compare to state values and return that Object

I've been trying for days to figure out the best approach and also how to make it work. I'm building a product page and each variation options is built dynamically (size, color) based on the GraphQL response it gets back. I'm used to simpler array checking but this one has me baffled and at a lost for even where to start.
So when a user clicks on "M" and "Red" it takes those values and stores them into state
// State Setup
const [variations, setVariations] = useState({});
// Set Variations State that was selected
function productVariationsHandler(event) {
setVariations({ ...variations, [event.target.name]: event.target.value });
}
// State Object after user has made their selections
{
"variations": {
"color": "Red",
"size": "XL"
}
}
I'm trying to take those user selected state variables ("Red", "XL") and match them to the GraphQL response in the variations object to get the databaseId and regularPrice
// GraphQL Response
{
"variations": {
"nodes": [
{
"attributes": {
"nodes": [
{
"attributeId": 237,
"name": "pa_color",
"value": "True Royal"
},
{
"attributeId": 220,
"name": "pa_size",
"value": "S"
}
]
},
"databaseId": 1846,
"regularPrice": "$24.95",
"salePrice": null,
"status": "publish"
},
{
"attributes": {
"nodes": [
{
"attributeId": 237,
"name": "pa_color",
"value": "Red"
},
{
"attributeId": 221,
"name": "pa_size",
"value": "XL"
}
]
},
"databaseId": 1847,
"regularPrice": "$24.95",
"salePrice": null,
"status": "publish"
}
]
}
}
I've tried using the find method and as well as map and even tried for as seen below but without avail
// My Failed Attempt
// Find the Variation based on user selected options
function findVariationProduct() {
for (const key in variations) {
product.variations.nodes.map((variation) => {
const variationProduct = variation.attributes.nodes.find(
({ value, name }) => {
if (name == `pa_${key}` && value == variations[key]) {
console.log(variationProduct);
}
}
);
});
}
}
Any help would be greatly appreciated!

How can we access the Child Key from Object

I'm trying to loop my child array but it's not working. It's working fine which it's first items but not working on the child elements.
"candidateApplication": [
{
"label": "Are you currently attending school?",
"id": "ap_currentschool",
"value": "",
"required": "N",
"type": "radio",
"display": null,
"list": [
{
"searchCode": "yes",
"searchValue": "yes"
},
{
"searchCode": "no",
"searchValue": "no"
}
],
"onSelect": [
{
"yes": [
{
"label": "Estimated Completion Date",
"id": "ap_compdate",
"value": "",
"required": "N",
"type": "date",
"display": null,
"list": null,
"onSelect": null
}
],
"no": null
}
]
},
]
I am easily access my data to looping lists like obj.candidateApplication.list But I am not able to loop through obj.candidateApplication.onSelect.yes.
Can anybody please guide me how can I fix that issue.
enter image description here
You are accessing obj.candidateApplication.onSelect.yes which is undefined because obj.candidateApplication.onSelect is an array of objects.
You probably want to loop over obj.candidateApplication.onSelect and then for each object you can access the yes property as you wish:
$.each(onSelect, function (index, element) {
$.each(element.yes, function (x, y) {
// your code here
})
});
Edit: As pointed by Heritic Monkey in the comments, obj.candidateApplication is an array as well, but in the picture attached to the question, there's already a local variable called onSelect, loop through that instead of obj.candidateApplication.onSelect because it's undefined. (at least it should be, we don't know what your code is doing)

Ember unknown relationship

I'm currently building software with Rails + Ember 3.12, but hitting a strange issue.
My models are the following:
// test-case-run
import DS from 'ember-data';
const { Model } = DS;
export default Model.extend({
testCase: DS.belongsTo('test-case'),
testCaseRunLogs: DS.hasMany('test-case-run-logs')
});
// test-case-run-log
import DS from 'ember-data';
const { Model } = DS;
export default Model.extend({
testCaseRun: DS.belongsTo('test-case-run'),
payload: DS.attr('')
});
And, my backend is returning the following payload:
{
"data": {
"id": "83",
"type": "test_case_run",
"relationships": {
"test_case": {
"data": {
"id": "90",
"type": "test_case"
}
},
"test_case_run_logs": {
"data": []
}
}
}
}
{
"data": {
"id": "83",
"type": "test_case_run",
"relationships": {
"test_case": {
"data": {
"id": "90",
"type": "test_case"
}
},
"test_case_run_logs": {
"data": [
{
"id": "426",
"type": "test_case_run_log"
}
]
}
}
},
"included": [
{
"id": "426",
"type": "test_case_run_log",
"attributes": {
"payload": "SCREENSHOT"
},
"relationships": {
"test_case_run": {
"data": {
"id": "83",
"type": "test_case_run"
}
}
}
}
]
}
I've got a custom adapter defining:
pathForType(type) {
return underscore(pluralize(type));
}
So, I think that everything should go well.
However, when I get into the ember inspector, I've got the following:
It seems that my relationship is not loaded properly.
And, I cannot access any data, such as:
log.get('testCaseRun') // that is null
run.get('testCaseRunLogs.length') // it returns 0
This is quite strange, as my records are loaded in the store, but not their relationships.
I have no idea on how to troubleshoot this, since the amount of information I can get from ember is quite limited (there is no error, the format looks good, ...).
Could someone help me to understand what's wrong with my calls? I've tried many things, such as renaming my models, but this does not improve the situation.
Moreover, this model is the only one, which I have problem with. All my other models don't have this problem. So, that's a bit weird.
Thanks a lot
The unknown in <(unknown):ember264> refers to the name of the class. That doesn't mean that your relationship is not loaded correctly. It's just Ember Data using anonymous classes.
To see the data of the relationship you could click on that string and afterwards on content. Another option is passing the full record to the console using the $E link in top right corner. Afterwards you could interact with the record on console, e.g. do a $E.get('testCaseRun.id').
By the way: You don't need to explicitly declare the model name on relationship definition if it's matches the dasherized property name. So testCaseRun: DS.belongsTo('test-case-run') is the same as testCaseRun: DS.belongsTo().
Try to declare hasMany relationship with the model name without 's'
testCaseRunLogs: DS.hasMany('test-case-run-log')
Finally, I've found the answer of my question.
The problem was that I was using the "underscore" form of the relationships:
"included": [
{
"id": "426",
"type": "test_case_run_log", <= HERE
"attributes": {
"payload": "SCREENSHOT"
},
"relationships": {
"test_case_run": {
"data": {
"id": "83",
"type": "test_case_run" <= HERE
}
}
}
}
]
And, changing pathForType was not sufficient.
So, I made my backend use dashes. And, it worked.

Postman: Wanted to validate data values getting from API in JSON format

I wanted to check some combinations of validations for values I am getting from API request in postmanlike
if "tracked": "Yes" then analytics > "transitTime": 239 should be present.
The snippet of API response:
{
"status": 200,
"data": [{
"id": 107267,
"branchId": "22",
"status": "1",
"googleETA": "2018-02-01 20:44:51",
"runDate": "2018-01-29",
"runOfTheDay": "1",
"ATD": "2018-01-29 14:02",
"simCarrier": "Vodafone",
"pingStatus": "Ok",
"driverName": "test",
"shipperCompanyId": "007",
"ETA": "2018-01-30 12:31:00",
"locationSource": "sim",
"created_at": "2018-01-29 07:05:54",
"updated_at": "2018-01-29 12:35:40",
"tracked": "Yes",
"analytics": {
"loadingTime": 55.62,
"unloadingTime": 0,
"transitTime": 239
},
"trackingStatusAtClosure": {
"Origin": "No",
"Transit": "No",
"Destination": "No"
}
}]
}
This is a very basic check and I would advise against using it anywhere other than practising in a local environment.
pm.test("Basic Check", () => {
var jsonData = pm.response.json().data
for(i = 0; i < jsonData.length; i++) {
if(jsonData[i].tracked === 'Yes') {
pm.expect(jsonData[i].analytics.transitTime).to.not.be.null
} else {
console.log('Tracked does not equal Yes')
}
}
})
As your data only has one item in the data array you don't really need to add the for loop but I added it in for you so you can see that the same check would run if you have more than one item. If the tracked property is 'Yes' then the test is checking if analytics.transitTime not null. Like I said, its a basic check and it's not doing a great deal but hopefully that will give you the information you need to get started.

Iterate through nested Javascript Objects from API response

I've tried 100 different things, and spend days looking through Google and Stackoverflow, but I can't find a solution to this problem. Everything I call after the body of this API response returns undefined!
The response from Facebook SDK looks like this:
[
{
"body": "[
"data": [
{
"name": "Larry Syid Wright",
"administrator": false,
"id": "xxx"
}, {
"name": "Melissa Long Jackson",
"administrator": false,
"id": "xxx"
}, {
"name": "Charlotte Masson",
"administrator": false,
"id": "xxx"
}
],
"paging": {
"next": "url"
}
]"
},{
"body": "{
"data": [
{
"id": "xxx_xxx",
"message": "In honor of Halloween, how many of you have your own ghost stories? Who believes in ghosts and who doesn't?",
"type": "status",
"created_time": "2014-10-31T20:02:01+0000",
"updated_time": "2014-11-01T02:52:51+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Joe HerBatman Owenby Jr."
}
],
}
"paging": {
"cursors":
{
"after": "xxx",
"before": "xxx"
}
}
}
},{
"id": "xxx_xxx",
"from": {
"id": "xxx",
"name": "Jessica Starling"
},
"message": "Watching the "Campaign" and I can't help but notice what a fantastic job they did (Will ferrell and all) with that North Carolina accent! Ya'll know we sound different than other southern states ;)",
"type": "status",
"created_time": "2014-11-01T02:36:21+0000",
"updated_time": "2014-11-01T02:36:21+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Scott Williams"n
}
]
}
}
],
"paging": {
"previous": "xxx",
"next": "xxx"
}
}"
}
]
This response is from a batch call. If I call them separately, I can easily iterate through the responses, and get everything from them. When I call them in the batch though, I can't get past "body", and I need to use a batch call.
console.log(response[0].body); will return the object inside the body of the first part of the response, but console.log(response[0].body.data); returns undefined. I just don't get it. This should be simple but it's like there's a lock on the door and I don't have the right key.
I normally have no issue iterating through objects, so I don't need a generalized answer. I need help seeing whatever it is here that I don't see. Why does the console show undefined when I call anything after the body, and what do I need to be doing to get any of these values?
That JSON contains nested JSON. body seems to be a string. Use
var body = JSON.parse(response[0].body);
The values from the body are just strings.which are embedded as json.So firstly you would need to parse them using JSON.parse.
The code would be like
var body = JSON.parse(response[0].body);

Categories