In the application generating dummy data every second and when I log it with "req.body" the output as below.
[
{
dataType: 'Number',
deviceName: 'device1',
attributeName: 'value',
min: '1',
max: '11',
value: '9.000438216772668',
ESP_OPS: 'i',
timestamp: '2020-05-28T20:08:56.544Z'
}
]
However I would like to get "value" in this array. When I try to log it with "req.body.value" it returns "undefined". How can I catch "value" in this array?
req.body returns an array. In this case the array only has 1 element (which is the json object that you want access to). In JavaScript array indices start at 0, therefore you need to writereq.body[0]
Just use req.body[0].value
The [0] statement have the function to reference the first element of the array.
Related
I have an array ["10","20"]
from this array i need to form an object as below. The elements in the array should point to "id" field in the json obejct. If there are more elements in the array that many times id field should come in the response.
input: ["10","20"]
expected response
{
id: "10",
id: "20:,
value1: true,// this key and value need to be hardcoded
value2: false //this key and value need to be hardcoded
}
I tried using the below option but it is not allowing duplicate keys in the response
var mapped = array.map(item => ({ "id": item.key }) );
console.log(mapped)
var newObj = Object.assign({}, ...mapped );
It will be a great help if anyone can help with this
You cannot have duplicate keys in Object
Every keys in object are unique while the values can be duplicate but not the keys
So if you have key id:'10' then the next time any value with obj["id"]=20 will overwrite the value 10
I am trying to add a search filter for a custom line item field in a suitelet and it is returning no results.
function getExpenseSearch(soNum){
log.debug('getExpenseSearch entered')
log.debug('soNum: ' + soNum)
var billSearch = search.create({
type: 'transaction',
filters: [
[ 'type', search.Operator.ANYOF , ['VendBill']], 'and',
['mainline', search.Operator.IS,['F']], 'and',
['custcol_connected_so', search.Operator.ANYOF, [soNum]] ///<=== this is the problem why is it not registering?
],
columns: ['trandate',
'tranid',
'amount'
]
}).run().getRange({start: 0, end: 100})
log.debug('return billSearch[0].tranid: ' + billSearch[0].tranid) //<== always undefined
return billSearch
}
I have isolated the problem to the sublist field
custcol_connected_so is a List field (of sales orders)
soNum is the netsuite internal id of the record
I have already tried the following:
changed .IS to to .ANYOF
used TEXT value instead of recID
hardcoded the correct recID
used 'expense.custcol_connected_so (and other variations, shot in the dark)
input different syntax for create filter
In the records browser there is no join table for the vendorBill so I would think just the custcol_connected_so filter should work fine.
Taking another look there are a couple of issues.
Your syntax for getting the tranid is incorrect (or at least not supported) and you would not be able to get the mainline amount with a single query because you are only going to be able to return the line level amount. In the example below you could use ref.id to load the sales order or to do a lookup Fields call:
This works in my account:
require(['N/search'], search=>{
search.create({
type:'creditmemo',
filters:[
['mainline', 'is', 'F'], 'AND',
['custcol_linked_transaction', 'anyof', [2403605]]
],
columns:['tranid', 'custcol_linked_transaction']
}).run().each(ref=>{
console.log(ref.id, ref.getValue({name:'tranid'}), ref.getValue({name:'custcol_linked_transaction'}));
return false;
});
});
If soNum is the visible sales order number you'd need to get the SO's internal id in order to run that search. Consider:
function getExpenseSearch(soNum) {
log.debug('getExpenseSearch entered')
log.debug('soNum: ' + soNum)
var soInternalId = null;
search.create({
type: 'salesorder',
filters: ['tranid', 'is', soNum]
}).run().each(function(ref) {
soInternalId = ref.id;
return false;
});
var billSearch = search.create({
type: 'vendorbill',
filters: [
['mainline', 'is', 'F'], 'and',
['custcol_connected_so', 'is', soInternalId] ///<=== this is the problem why is it not registering?
],
columns: ['trandate',
'tranid',
'amount'
]
}).run().getRange({
start: 0,
end: 100
})
log.debug('return billSearch[0].tranid: ' + billSearch[0].tranid) //<== always undefined
return billSearch
}
Hello these code does request to Steam Web API
const request = require("request");
request({
url: "https://api.steampowered.com/IEconService/GetTradeOffers/v1/?key=MYAPIKEY&get_sent_offers=1&active_only=1&format=json",
json: true
}, (err, responser, body) => {
console.log(body.response['trade_offers_sent']);
});
And this is what it returns:
{
trade_offers_sent: [
{
tradeofferid: '3974708687',
accountid_other: 82613664,
message: 'test message',
expiration_time: 1587017229,
trade_offer_state: 9,
items_to_give: [Array],
is_our_offer: true,
time_created: 1585807629,
time_updated: 1585807629,
from_real_time_trade: false,
escrow_end_date: 0,
confirmation_method: 2
}
]
}
But when i'm trying to get value of accountid_other this way:
console.log(body.response['trade_offers_sent'].accountid_other);
it returns undefined
The square brackets [ ... ] within trade_offers_sent indicate that it holds an array and not just a single item (it just happens to be a single item in the array). Thus to obtain you value you are interested in you need to specify the index of the item you want or use a loop to go through it. In this case you want the first item and you can use ['trade_offers_sent'][0] to obtain it.
I have a more than one inputs with numbers so I need a output that look like this:
[1, 1, 1, 1, 1] but instead of that it output this in console log: ["1", "1", "1", "1", "1"] and in mongodb like this: ["1,1,1,1,1"].
In models if I set to be like this:
numbers: {
type: Number,
required: true
}
This is code that I use for mongodb with mongoose:
router.post('/', (req, res)=>{
const newResult = Result({
numbers: req.body.numbers
});
newResult.save()
.then(savedResult=>{
ElectoralUnit.find({})
.then(electoralUnits=>{
res.redirect('/results');
});
});
});
I get the following Error:
error: (node:5696) UnhandledPromiseRejectionWarning: ValidationError: StateResult
validation failed: numbers: Cast to Number failed for value "[ '1', '1', '1', '1', '1' ]"
at path "numbers"
I tried to put type: [Number] but no luck.
but if I set to String instead of number then is without error but string instead of integer in mongodb. How to set array to integer?
Since you are attempting to store an array of Numbers, and since Mongoose will convert number-like strings into JavaScript Numbers, you need to make sure you are in fact storing an Array of Numeric Digits and define your Scheme-type as
numbers: {
type: [Number],
required: true
}
Be sure to validate inputs on both the front-end and back-end. To avoid the UnhandledPromiseRejectionWarning, be sure to add a .catch() to your .save() function and send the appropriate response to your front end.
The documentation for node module dbus-native is weak, and the none of the many examples apply to my use case, which seems like it ought to be simple.
My problem is trying to make a simple method call into the "connman" network manager. I can make a request (invoking GetProperties method) just fine, and get a complex structure back and generally figure out how to get data out of it. But when I try to send something back with SetProperty, I just can't figure out how to get my data into the form it wants.
There's not really any documentation about how to translate to and from DBus's type system and node's. I gathered from source that variant types are arrays with signature and value, e.g., [ 's', 'string ], but no matter how I try to massage the data I'm trying to send to SetProperty, I get an "Invalid struct data" error.
The SetProperty method I'm trying to call has an argument signature "sv"--name, value. The particular property I'm trying to set has a value with is itself (as far as I can determine--there's precious little documentation on that side as well) an "a{sv}". that is,property is a hash of property names and values. My initial attempt as calling this function was:
var sysbus = require('dbus-native').systemBus();
sysbus.invoke({
path: '/net/connman/service/ethernet_1cba8cfa0e57_cable',
destination: 'net.connman',
'interface': 'net.connman.Service',
member: 'SetPropertry',
signature: 'sv',
body: [
'IPv4.Configuration', [
'a{sv}',
{ 'Method': [ 's', 'dhcp' ] }
]
],
type: dbus.messageType.methodCall
}, function (err, res) {
// etc...
});
This gives me the "Invalid struct data" error. I've tried man other ways to wrap the data in arrays, hashes, etc., and just can't seem to find the right answer. I'm trying to emulate this working Python code:
import dbus
bus = dbus.SystemBus()
service = dbus.Interface(bus.get_object("net.connman",
"/net/connman/service/ethernet_1cba8cfa0e57_cable",
"net.connman.Service");
conf = { "Method": make_string_variant("dhcp") }
service.SetProperty("IPv4.Configuration", conf);
Any ideas?
I recently started using dbus-native for connman and also had problems with all the nested arrays. I'll be improving the marshaling/unmarshaling in the fork of the project at https://github.com/Digisoft-tv/node-dbus - you might want to have a look. Hopefully my changes will be accepted up-stream.
Anyway, to get it working now, the format of the parameters you need to pass in is as below:
mgr.CreateSession([ [ 'key', [ 's', 'value' ] ], [ 'key2', [ 'i', 2 ] ] ], '/object/path', function(error, response) {
if (error) {
return console.error('SetProperty error:', error);
}
console.info('SetProperty response', response);
});
The outermost array is the "object" (ARRAY of dict entries).
Each nested array holds a key-value pair (DICT ENTRY). key at index 0 and value at index 1.
The values is a variant, which is always encoded as an array, with "signature" at index 0 and the actual value at index 1.
Hope it helps.
The correct way to encode 'a{sv}' is [ ['string', ['signature', 'value']], ... ]
Arrays ( a ) are encoded as normal JS arrays as well as structs / hashes ( () / {} ). I'll probably add shortcut to allow JS object to be used in place of a{sv} but at the moment input has to be quite verbose.
var sysbus = require('dbus-native').systemBus();
sysbus.invoke({
path: '/net/connman/service/ethernet_1cba8cfa0e57_cable',
destination: 'net.connman',
'interface': 'net.connman.Service',
member: 'SetPropertry',
signature: 'sv',
body: [
'IPv4.Configuration', [
'a{sv}',
[ // a
[ // {
'Method', [ 's', 'dhcp' ] // sv
]
]
]
],
type: dbus.messageType.methodCall
}, function (err, res) {
// etc...
});