I have this statement :
const {
'xsi:Event': {
'xsi:eventData': [
{
'xsi:call': [
{
'xsi:extTrackingId': [extTrackingId],
'xsi:personality': [personality],
'xsi:internalReleaseCause': [releaseCause],
},
],
},
],
},
} = data
I'm parsing complicate object from some api. On top is real example of object. In some cases, i have same structure, but without property 'xsi:internalReleaseCause', so in this case i cant define a value for releaseCause constant.
Question is how to check if 'xsi:internalReleaseCause' prop exists, on the fly?
const data= {
'Event': {
'eventData': [
{
'call': [
{
'extTrackingId': [],
'personality': [],
'internalReleaseCause': ['hi'],
},
],
},
],
},
}
var { Event: {eventData: [{call:[{extTrackingId:[],personality:[],internalReleaseCause}]}]} } = data;
console.log(internalReleaseCause[0])
we can use this object destruction to identify internalReleaseCause on the fly but you have some special characters (:) in object keys. I am not sure how to escape them but if there is a way you can get rid of them, then the below snippet works and you can identify the object directly. Hope this helps!
Related
I'm trying to come up with a method that would allow me to create a it block that confirms whether my configuration file has a specific attribute. The object has in it:
exports.config = {
services: [
['sauce', {
sauceConnect: true,
}]
],
}
I would like to have an it block that would confirm whether this value is true and if it isn't, then it should fail.
I have tried a couple approaches like if (sauceConnect in services) etc but it isn't an approach that is working. The test and the configuration file are in separated documents and for the life of me I can't work out a good enough test.
I'd appreciate any help or answers here.
On the assumption that this is how you want your config to look like, you'll have to loop through it and find the match:
const exportedConfig = {
services: [
['sauce', {
sauceConnect: true,
}],
['key', {
data: "value",
}]
],
}
// [1] refers to the 2nd element in the array, aka the value
// some looks for ANY match and if a match occurs it returns true.
console.log(exportedConfig.services.some(element => element[1].sauceConnect == true ))
Though, a recommendation would be to format your config as so:
const exportedConfig = {
services: {
sauce: {
sauceConnect: true,
},
key: {
data: "value",
}
},
}
``
So I am having trouble figuring out how to create an array with two objects, looping through my object and adding some values to those objects in Javascript. Currently I have the following mock response:
const mockResponse =
{
"errors": [
{
"errorKey": "ERROR_NO_DELIVERY_OPTIONS",
"errorParameters": [
{
"errorMessage": "ERROR_DELIVERY_OPTIONS_YOU_SELECTED_NOT_AVAILABLE_NOW",
"partNumbers": [
19308033,
19114798
]
},
{
"errorMessage": "Ship to Home not available for these orderItemId",
"orderItemIds": [
10315031,
10315032
],
"availableShipModeId": 13203
},
{
"errorMessage": "Pickup At Seller not available for these orderItemIds",
"orderItemIds": [
10222222,
10333333
],
"availableShipModeId": 13203
}
],
"errorMessage": "ERROR_NO_DELIVERY_OPTIONS",
"errorCode": "ERROR_NO_DELIVERY_OPTIONS"
}
]
}
I would like to have an array with two objects. One for the first error message("Ship to home...") and another for the second error message("Pickup at Seller..."). I would like to then loop through the JSON and add each "orderItemIds" to there respective object. For example, 10315031,10315032 would go to the first object and 10222222, 10333333 to the second.
You can use reduce to loop through your errors and use the errorMessage property as a key
const result = mockResponse.errors[0].errorParameters.reduce((prev, item) => {
const { errorMessage, orderItemIds } = item;
if (prev[errorMessage]) {
prev[errorMessage] = [...prev[errorMessage], ...orderItemsIds];
} else {
prev[errorMessage] = orderItemIds
}
return prev
}, {})
Let me know if this does answer your question
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/
I want to sort a JSON array based on time value in a subarray with the key names of the subarrays being named uniquely.
I'm searching for the method to access key, value update_time of every element in Products so I can use that value in a sorting script.
I have tried sorting the array but can not determine how to access the key, values of the subarrays
Expected behavior should be that every unique_keyname_# element is available for sorting and is sorted for further processing in JavaScript. Ultimately with the newest unique_keyname_# as the first element in a list, based on the update_time key.
var obj = {
"company": {
"department_1": {
"Products": {
"unique_keyname_1": {
"product_owner": "co-worker-1",
"update_time": "unix_timestamp_1"
},
"unique_keyname_5": {
"product_owner": "co-worker-4",
"update_time": "unix_timestamp_45"
},
"unique_keyname_8": {
"product_owner": "co-worker-2",
"update_time": "unix_timestamp_5"
}
}
},
"department_2": {
"Products": {
"unique_keyname_3": {
"product_owner": "co-worker-1",
"update_time": "unix_timestamp_21"
},
"unique_keyname_6": {
"product_owner": "co-worker-2",
"update_time": "unix_timestamp_7"
},
"unique_keyname_4": {
"product_owner": "co-worker-3",
"update_time": "unix_timestamp_75"
}
}
}
}
}
I solved the issue by writing an intermediate script in python which makes the API response a valid array. From there it was fairly easy to sort the data.
Thanks for the replies confirming the data itself was deliverd to me in an inappropriate format!
regards
In your example, there are no arrays.
Anyway, in Javascript you can access a node using . like:
obj.company.department_1.Products.unique_keyname_1
Or using [] which gives you more freedom to use costume fields
obj["company"]["department_1"]["Products"]["unique_keyname_1"]
// can also be more dynamic as:
obj["company"]["department_"+ department_counter]["Products"]["unique_keyname_" + keyname_counter]
Is there a possibility that you will change the structure of your JSON? to make it more manangeable ?
if so, i would recommend the folowing structure:
var products = [
{
department: 'SomeDepartment',
productName: 'Something',
productOwner: 'Someone',
update_time: 'Sometime'
}
]
Then you can sort the array easy using Array.sort()
for the sort topic use this : Sort array of objects by string property value
Jsonlint display that this JSON object is valid:
[{"obj":{"markers":"[{\"k\":47.040182144806664,\"B\":0.52734375},{\"k\":50.90303283111257,\"B\":10.37109375},{\"k\":52.53627304145945,\"B\":-1.7578125},{\"k\":41.77131167976406,\"B\":-6.591796875}]","path":"[[47.040182144806664,0.52734375],[50.90303283111257,10.37109375],[52.53627304145945,-1.7578125],[41.77131167976406,-6.591796875]]"}}]
I'm trying to access to markers with the k, B and path elements but it's always set to undefined. Here is my code:
try {
var jsonData = JSON.parse(myJson);
console.log(jsonData.obj[0].markers[0].k);
}
catch (e) {
console.error("Parsing error:", e);
}
Can someone tell me how to access to the element of my JSON object properly? Thanks for the help.
Something must have gone wrong in creating this string. Yes, it's valid JSON, but it has a different format than you think, because you escape control characters like " and [, ].
Try this string instead:
[
{
"obj":{
"markers":[
{
"k":47.040182144806664,
"B":0.52734375
},
{
"k":50.90303283111257,
"B":10.37109375
},
{
"k":52.53627304145945,
"B":-1.7578125
},
{
"k":41.77131167976406,
"B":-6.591796875
}
],
"path":[
[
47.040182144806664,
0.52734375
],
[
50.90303283111257,
10.37109375
],
[
52.53627304145945,
-1.7578125
],
[
41.77131167976406,
-6.591796875
]
]
}
}
]
as opposed to your string:
[
{
"obj":{
"markers":"[{\"k\":47.040182144806664,\"B\":0.52734375},{\"k\":50.90303283111257,\"B\":10.37109375},{\"k\":52.53627304145945,\"B\":-1.7578125},{\"k\":41.77131167976406,\"B\":-6.591796875}]",
"path":"[[47.040182144806664,0.52734375],[50.90303283111257,10.37109375],[52.53627304145945,-1.7578125],[41.77131167976406,-6.591796875]]"
}
}
]
You have two issues from what I can tell:
One, yes it is valid Json but the marker and path object values are enclosed in string quotes:
"markers":"[{\"k\":47.040182144806664,\"B\":0.52734375},{\"k\":50.90303283111257,\"B\":10.37109375},{\"k\":52.53627304145945,\"B\":-1.7578125},{\"k\":41.77131167976406,\"B\":-6.591796875}]",
"path":"[[47.040182144806664,0.52734375],[50.90303283111257,10.37109375],[52.53627304145945,-1.7578125],[41.77131167976406,-6.591796875]]"
what you rather want is:
"markers":[{"k":47.040182144806664,"B":0.52734375},{"k":50.90303283111257,"B":10.37109375},{"k":52.53627304145945,"B":-1.7578125},{"k":41.77131167976406,"B":-6.591796875}],
"path":[[47.040182144806664,0.52734375],[50.90303283111257,10.37109375],[52.53627304145945,-1.7578125],[41.77131167976406,-6.591796875]]
But given the above, also not escape the k and b object names for markers \"k\" should be "k":
So the completed edited JSON would look like this:
[{"obj":{"markers":[{"k":47.040182144806664,"B":0.52734375},{"k":50.90303283111257,"B":10.37109375},{"k":52.53627304145945,"B":-1.7578125},{"k":41.77131167976406,"B":-6.591796875}],"path":[[47.040182144806664,0.52734375],[50.90303283111257,10.37109375],[52.53627304145945,-1.7578125],[41.77131167976406,-6.591796875]]}}]