I've got a problem by checking this json properties. I want to test, if the formName is "TestForm_WF1", but I dont know how to write the test to check the properties of this strange named array:
{
"#!#": [
{
"_type": "wfdocument",
"formName": "TestForm_WF1",
normally I got some Output like
[
{
"_type": "application",
...
which I could test with the following forEach-function:
var response = JSON.parse(responseBody);
response.forEach( function(entry) {
test["foo"] = entry._type === "application";
...
});
other way round was that properties have thier own properties and could be tested like:
Output:
{
"license": {
"_type": "license",
...
Testcase:
var jsonData = JSON.parse(responseBody);
tests["bar"] = jsonData.license._type === "license";
Use a bracket notation for characters that can't be used with a dot notation:
var response = JSON.parse(responseBody);
response["#!#"].forEach( function(entry) {
test["foo"] = entry._type === "application";
...
});
Related
I'm working on a side project of a currency converter. I've made an API Call and this is all the data it sent me (this varies depending on the selected currencies so USD_GBP could be CAD_JPY):
{
"query": {
"count": 1
},
"results": {
"USD_GBP": {
"id": "USD_GBP",
"val": 0.733695,
"to": "GBP",
"fr": "USD"
}
}
}
In my express code I've set up the HTTPS Module:
https.get(url, function(response) {
response.on("data", function(data) {
const currencyData = JSON.parse(data);
const exchangeRate = currencyData.results.USD_GBP.val;
});
});
});
The problem you can probably see is that since the currency to convert from and convert to are always changing the constant exchangeRate doesn't work for any scenario besides converting from USD to GBP. So I'm wondering how to make that work for every combination that I throw at it. Above my HTTPS get request I already made a variable (const combine = firstCurrency + "_" + secondCurrency;) that combines the selections. I tried concatenating it to the exchangeRate variable, but it gave me an error that it can't find the value of undefined.
JavaScript objects allow you to use bracket notation for dynamic variables names.
var obj = { bar: 'baz'; }
var foo = 'bar';
obj.foo ; // This is invalid, as it looks for the "foo" property
obj[foo]; // This is valid, as it looks for the "bar" property we want
Since you mentioned you have a variable named combine already, you should be able to use bracket notation on the results:
const exchangeRate = currencyData.results[combine].val;
Here's a quick little snippet:
var firstCurrency = 'USD';
var secondCurrency = 'GBP';
const combine = firstCurrency + "_" + secondCurrency;
var response = `{
"query": {
"count": 1
},
"results": {
"USD_GBP": {
"id": "USD_GBP",
"val": 0.733695,
"to": "GBP",
"fr": "USD"
}
}
}`;
const currencyData = JSON.parse(response);
const exchangeRate = currencyData.results[combine].val;
console.log( exchangeRate );
If you didn't have the combine variable, you could always use Object.keys() to get the keys from the result and use that, but it's arguably uglier (especially since you already know the key):
const exchangeRate = currencyData.results[Object.keys(currencyData.results)[0]].val;
Instead of currencyData.results.USD_GBP.val, use currencyData.results['USD_GBP'].val
You can even use a variable as well. :
currencies = ['USD_GBP', 'EUR_USD']
currenceis.forEach(currency => {
currencyData.results[currency].val
}
Changed Example:
https.get(url, function(response) {
response.on("data", function(data) {
const currencyData = JSON.parse(data);
const exchangeRate = currencyData.results['USD_GBP'].val;
});
});
});
You can use the backtick syntax.
let firstCurrency = "USD";
let secondCurrency = "GBP";
const currencyData = {
"query": {
"count": 1
},
"results": {
"USD_GBP": {
"id": "USD_GBP",
"val": 0.733695,
"to": "GBP",
"fr": "USD"
}
}
};
const exchangeRate = currencyData.results[`${firstCurrency}_${secondCurrency}`].val;
console.log(exchangeRate);
I have an object and I’m trying to find a specific value using an ID in ECMAScript6.
I’ve tried something like this: myvalue = this.json.find(x => x == '1234');
The JSON looks something like this:
{
"results": [
{
"abcde1234": {
"value": 4
}
},
{
"zxcv4567": {
"value": 2
}
}
]
}
All the examples I’ve found can only find off named key-value pairs.
Try
json.results.find(x => /1234/.test(Object.keys(x)[0]));
json = {
"results": [
{
"abcde1234": {
"value": 4
}
},
{
"zxcv4567": {
"value": 2
}
}
]
}
let r = json.results.find(x => /1234/.test(Object.keys(x)[0]));
console.log(r);
const json = {
'1234': { 'value' : 4},
'5678': { 'value' : 10}
};
const value = json['1234'];
console.log(value);
The JSON data doesn't seem proper.
But in case you are finding by key, you can directly access this, something like:
Parsed JSON maps directly to JavaScript types: Object, Array, boolean, string, number, null. Your example used find() which is (normally) a method used with arrays. If your JSON was structured like this, you could expect to use find:
const jsonString = '["a", "b", "c"]';
const jsonData = JSON.parse(jsonString);
jsonData.find(x => x === "a"); // "a"
But it seems like your data is structured as an object, so you can use normal property access:
const jsonString = '{"1234": {"value": 4}, "5678": {"value": 10}}';
const jsonData = JSON.parse(jsonString);
jsonData["1234"] // {value: 4}
jsonData["1234"].value // 4
EDIT
OP changed the data example, so the above code is less directly applicable, but the general point is: once you parse it, it's just javascript.
I'm trying to remove an object from Json Object it works..but it replace it with null..i dont know why, how can i remove the null value from the json..heres the function :
company.deleteExternalLinkFromGrid = function (row, matricule) {
// console.log('Inside of deleteModal, code = ' + code);
//$scope.sitting= {};
console.log(matricule);
//console.log(JSON.stringify(linkJsonObj));
delete linkJsonObj[matricule];
console.log(JSON.stringify(linkJsonObj));
};
heres the object:
[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null]
You can use filter(), x will be without null's.
function test()
{
var x =[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null].filter(isNotNull);
alert(JSON.stringify(x));
}
function isNotNull(value) {
return value != null;
}
fiddle
There are multiple ways to delete an object from an array of objects in JavaScript. You don't need AngularJS for that, you can use VanillaJS.
If you just want the nulls filtered you can use
var yourArray =[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null];
yourArray = yourArray.filter(function(elt){
return elt != null;
});
But this loses the original reference to your object.
If you want to keep the reference, Use array.splice().
yourArray.forEach(function(){
yourArray.splice(yourArray.indexOf(null),1);
});
now you will have null less array in yourArray. This actually deletes an object from an array without changing the reference,
delete will replaced the object with undefined
You can filter the array to remove them using Array#filter()
var array = [{
"name": "xxx",
"link": "www.ddd.com",
"id": 0,
"$$hashKey": "uiGid-001Z"
}, {
"name": "xx",
"link": "www.dddcom",
"id": 1,
"$$hashey": "uiGrid-0029"
}, {
"name": "xxx",
"link": "www.ddd.com",
"id": 2
}];
delete array[1];
array = array.filter(a=>a);
console.log(JSON.stringify(array));
Using a fetch request to get some data. The JSON object path depends on a string variable. How would I convert the string into an object that can be referenced as an array in the path. Here's my code:
var path = 'bob';
fetch(request)
.then(function(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response.json();
}).then(function(json) {
var data = json.message.path[0].text;
}).catch(function(error) {
console.log(error);
});
JSON:
{
"message": {
"bob": [
{
"name_id": "3351",
"name": "bob",
"text": "lorem ipsum"
},
{
"name_id": "34562",
"name": "bob",
"text": "lorem ipsum2"
}
]
}
Basically, path defines the correct object to be used in the dot notation. BUT - the object also has to be able to reference the array.
Any solutions?
You could try using:
var data = json.message[path][0].text;
where path is the name of the object as you defined:
path = "bob";
If you have a path variable in the format user.index, you could reference the corresponding message in your JSON like this:
path = path.split(".");
var name = path[0], index = path[1];
var data = json.message[name][index].text;
If path is "bob.1", data would become "lorem ipsum2"
json.message[name] evaluates to the array of messages. To index into that array, just put brackets after the value, like any other array: json.message[name][index], which is equivalent to (json.message[name])[index], which is equivalent to var array = json.message[name] then array[index].
Note that this solution does no error checking, and will throw an error if the given user isn't in json.message.
I am very new to development and I am trying to figure out the best way to convert a current export tool I wrote that exports a JSON object to now include a JSON object that has an array of objects on the inside. What I am referring to is the array of objects on profile: I tried using .push() to put the objects into the array but I am lost.
Ideal JSON object
{
"id": "220a5f58-480e-45c3-8252-b3712d9e6c32",
"name": "hello",
"profile": [
{
"fullName": "test",
"displayName": "test",
"number": "Unknown",
"attributes": {
"identifier": true,
"categorical": false,
"quantized": false,
"relational": false,
"ordinal": false
}
},
{
"fullName": "test",
"displayName": "test",
"number": "Unknown",
"attributes": {
"identifier": true,
"categorical": false,
"quantized": false,
"relational": false,
"ordinal": false
}
}
],
"test": 12
}
JS Code
// object.profile is a JSON object
export.profile = [];
angular.forEach(object.profile, function (value, key) {
//export.profile[key] = {};
export.push(profile[key] );
export.profile[key].attributes = {};
export.profile[key].fullName = (value['original-name']);
export.profile[key].displayName = (value['display-name']);
export.profile[key].interpretation = (value['interpretation']['iName']);
export.profile[key].mainType = (value['main-type']);