Get value from Request URL response data - javascript

Requested URL sent - https://www.example.com/detail.guest.html?ppc=FDE466920006DCEFA697BF982FC9C87C5B257ECB2230CBF4D6D6CA740C7B894D5795F70DED928ED3B00C1F3F77DF974DFD73882DEBDD7EC063B37DEB24CF655528FD911109C57961AE314C612772AADFD2E193D572E6F6C8E249A6DAA
Get below response data correctly as expected by 3rd party.
BookersID=250100000002;BookersTitle=Mr;BookersFirstName=test1;BookersLastName=test2
I want to extract "BookersID", "BookersTitle", "BookersFirstName", "BookersLastName" separately and display this value in input field.
JS:
var bookerID = data[0].BookersID;
var bookerTitle = data[0].BookersTitle;
var bookerFname = data[0].BookersFirstName;
var bookerLname = data[0].BookersLastName;
console.log("BookersID", bookerID);
console.log("BookersTitle", bookerTitle);
But getting error in display value.
Please let me know how to get the value in console log?
Thanks

First you need to get data from your xhr request. To do that you need to add callback function. (More info in jQuery.get() documentation)
$.get( endpoint, function( data ) { // add callback to handle response
// ... parse data here
});
As I understand you need to parse data. It could be done by using String.prototype.split method and simple mapping.
console.log(data) // BookersID=250100000002;BookersTitle=Mr;BookersFirstName=test1;BookersLastName=test2
var parsed = data.split(';').map(part => ({ name: part.split('=')[0], value: part.split('=')[1] }));
console.log(parsed);
Output:
[
{name: "BookersID", value: "250100000002"},
{name: "BookersTitle", value: "Mr"},
{name: "BookersFirstName", value: "test1"},
{name: "BookersLastName", value: "test2"}
]
If you want to get data as an object:
var parsedObject = parsed.reduce(
(obj, item) => Object.assign(obj, {[item.name]: item.value}) ,{});
// {BookersID: "250100000002", BookersTitle: "Mr", BookersFirstName: "test1", BookersLastName: "test2"}

If you getting the same response you need to write a utility function to convert the same into an object
function _convert(responseString) {
var _obj = {};
responseString.split(";").forEach(function(pair){
var _pairArr = pair.split("=");
_obj[_pairArr[0]] = _pairArr[1];
});
reuturn _obj;
}
var responseString = "BookersID=250100000002;BookersTitle=Mr;BookersFirstName=test1;BookersLastName=test2";
var obj = _convert(responseString);
obj['BookersID']; // 250100000002
// or
obj.BookersID; // 250100000002
Note: This will only work if your response has exactly the same format as you have mentioned.

var str = 'BookersID=250100000002;BookersTitle=Mr;BookersFirstName=test1;BookersLastName=test2';
var data = {};
var parsed = str.split(';').map(part => { let x = part.split("="); data[x[0]] = x[1]; console.log(x) });
console.log(data)
Output:
{BookersID: "250100000002", BookersTitle: "Mr", BookersFirstName: "test1", BookersLastName: "test2"}

You could use .reduce() and .split() to create your string into an object, which can then have its properties accessed
const data = "BookersID=250100000002;BookersTitle=Mr;BookersFirstName=test1;BookersLastName=test2";
const dataObj = data.split(';').reduce((acc, kvp) =>
({
...acc,
...(([key, value]) => ({[key]: value}))(kvp.split('='))
}), {});
console.log(dataObj);
// access properties:
console.log(dataObj.BookersID);

Related

JavaScript: How can I insert an Object into an Array of Objects?

I have this script that takes data from a JSON with almost 100 data, then uses this data to bring the weather from an API and after that, inserts this data into an object (using a for for creating my 100 objects), I would like to add the objects that have a temperature > 99 in one array and the ones that have a temperature < 99 into another I have tried this way but doesn't seem to work, sorry if it's a super fool mistake that I can't see, thanks for your help!
This is my script:
async function calcWeather(){
const info = await fetch('../json/data.json')
.then(function(response) {
return response.json()
});
for (var i in info) {
const _idOficina = info[i][0].IdOficina
const _nombreOficina = info[i][0].NombreOficinaSN
const _zona = info[i][0].Zona
const _estado = info[i][0].NombreEstado
const lat = info[i][0].latjson
const long = info[i][0].lonjson
const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`
fetch(base)
.then((responses) => {
return responses.json()
})
.then((data) => {
// console.log(data)
var myObject = {
Id_Oficina: _idOficina,
Latitud: data.coord.lat,
Longitud: data.coord.lon,
Ciudad: data.name,
Estado: _estado,
Zona: _zona,
Nombre_Oficina: _nombreOficina,
Temperatura: data.main.temp,
Descripcion: data.weather[0].description
};
// validation
if (myObject.Temperatura < 99){
var lstValid = [];
function pushValid(){
lstValid.push(myObject[i]);
}
pushValid();
console.log(pushValid())
}
});
}
};
Your array is local, so for every object you create new lstValid array with no previous data. The solution is to create the array before fetching the data or before the loop:
async function calcWeather(){
var lstValid = []; // HERE
const info = await fetch('../json/data.json')
.then(function(response) {
return response.json()
});
var lstValid = []; // OR HERE (ONLY ONE OF THEM)
for (...) {
...
}
You'll probably be best served by creating the array outside of that call since you're clearing it every run. Then simply add your object. Like Trincot's comment, i'm not sure what exactly you're indexing.
async function calcWeather(){
var lstValid = [];
....
if (myObject.Temperatura < 99){
lstValid[someindex] = myObject;
}
else{
lstNotValid[someOtherIndex] = myObject;
}
}

How to set Key/Value pair to chrome.storage.sync

I am trying something simple with a Chrome Extension, but the documentation I have found is not clear enough regarding the structure of the methods to use the chrome storage. I have the following code (generic) to store and retrieve some values:
var value = 561;
var key = "abc";
chrome.storage.sync.set({ [key] : value });
chrome.storage.sync.get(key, ({ result }) => {
console.log("value received is: " + result); // This does not work, result = undefined
});
If I want to retrieve the key added to the store, what is wrong with the previous code?
When using { result } you are extracting result from the first parameter being passed.
Should be instead:
var value = 561;
var key = "abc";
chrome.storage.sync.set({[key]: value });
chrome.storage.sync.get(key, ({ abc }) => {
console.log("value received is: " + abc);
});
// or
chrome.storage.sync.get(key, (result) => {
console.log("value received is: " + result.abc);
});
TLDR;
In JavaScript, when adding { result } you are extracting that variable from the underlying object in this case, the parameter.
Assuming the object is:
const results = {
a: 1,
b: 2,
c: 3
}
You can simplify the parameters to be like:
const { a, b ,c } = results
which is similar to:
const a = results.a
const b = results.b
const c = results.c
Since the first argument in your function is now { result }, it is expecting that key to exist in the first argument of that function. But it doesn't, it should be instead{abc}

Setting application/json as the data during the dragstart in HTML5 DND

I observed the setting the JSON data in HTML5DND will be converted into string. Are there any alternatives and best practices for passing JSON Data other than stringifying.
// During drag enter
event.dataTransfer.setData('application/json', {
id: 1
});
// During Drop data is printing as object
let data = event.dataTransfer.getData('application/json');
// printing [object Object]
There is no alternative for DataTransfer.setData() because its data (second) argument is a DOMString.
There is an alternative to DataTransfer--DataTransferItem; however, using it will involve stringifying the object (to pack that into a Blob of mimetype JSON).
In case my other answer does not answer your question, try dragging/dropping the object avatars into the textarea.
const object_1 = {id: 1}
const object_2 = {id: 2}
const p_1 = document.body.appendChild(document.createElement("p"))
const p_2 = document.body.appendChild(document.createElement("p"))
p_1.innerText = "object_1"
p_1.draggable = true
p_2.innerText = "object_2"
p_2.draggable = true
p_1.ondragstart = function () {
event.dataTransfer.setData("text", "object_1")
}
p_2.ondragstart = function () {
event.dataTransfer.setData("text", "object_2")
}
const textarea = document.body.appendChild(document.createElement("textarea"))
textarea.ondrop = function() {
event.preventDefault()
this.innerText = eval(event.dataTransfer.getData("text")).id
}

MongoDB Node-Red Update

I want to update data in my MongoDB with Node-Red using mongodb3 node.
This is my function before the mongo node:
var payload = msg.payload;
var newMsg = {payload: {}};
var doc = {
$set:{
temp:23,
hum:99
}
};
newMsg.payload.selector= {address: payload.address};
newMsg.payload.document = doc;
newMsg.payload.options = {upsert: true};
return newMsg;
I got this error:
UnhandledPromiseRejectionWarning: MongoError: document must be a valid
JavaScript object.
Anyone knows what to do?
Try the following:
var newMsg = msg;
newMsg.collection = '<insert your collection name>';
newMsg.operation = 'update';
newMsg.payload = {
{},
$set:{
"temp":23,
"hum":99
}
};
return newMsg;
The mongodb3 documents says about
msg.payload -
To pass a single parameter to an operation use msg.payload as your
parameter (eg {_id: 1243}).
To pass multiple parameters to an operation fill msg.payload with
an array.
If you want to pass a single parameter WHICH IS AN ARRAY (eg as
with InserMany), wrap your array in an outer array: msg.payload =
[[{_id: 1243}, {_id: 2345}]]
msg.payload is actually parameters to a operation method ('insert', 'update',...).
You can find document for parameters for all the methods here
In your case:
var newMsg = msg;
newMsg.collection = 'collection-name';
newMsg.operation = 'update';
newMsg.payload = [
{}, // filter
{ // update
"$set": {
"field to be updated": "value to be updated",
...
}
},
{} // options [optional]
function() {} // callback [optinal]
];
return newMsg;

using json objects in URLSearchParams

Is it possible to somehow append json objects onto a URLSearchParams object?
So instead of:
urlSearchParams.append('search', 'person');
it's:
urlSearchParams.append({search: "person"});
My answer courtesy of Darshak Gajjar's answer
Can use json objects via this way:
let test_this = [{"search": "person"}, { search: "another person"}];
var json = JSON.stringify(test_this);
urlSearchParams.append("myobj", json);
return this.http.post(this.post_url, urlSearchParams, options) //options being your own RequestOptions
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Something like this might work urlSearchParams = Object.assign(urlSearchParams, {search: "person"});
EDIT: Alternate solution using vanilla javascript. Also, I thought URLSearchParams was just a normal js object, but in fact you have to use get, set and append to access properties.
var params = new URLSearchParams("a=apple&b=balloon");
var parametersToAdd = {c: "car", d: "duck"};
for(key in parametersToAdd)
params.append(key, parametersToAdd[key]);
console.log(params.get('c'));
console.log(params.get('d'));
EDIT bis:
.append() supports to re-use the same key/parameter name, while .set() would have overwritten a previous value.
May be using below code you can pass entire json object in URL Search param
var json = JSON.stringify(myObj);
this.http.get('url'+'?myobj='+encodeURIComponent(json))
There's no API for that. You just need to enumerate over the properties and append them manually, for example using the following function:
function appendParams(params: URLSearchParams, obj: any) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
params.append(key, obj[key])
}
}
}
appendParams(urlSearchParams, { search: 'person' });
Want to share my answer for Angular2 with the option of sending an Array
This is how I use this get function:
this.get('/api/database', {
'age': [1,2,3,4]
})
And the service is something like:
get(url, _params = {}) {
let params = this._processParams(_params);
return this.http.get(url, params).toPromise();
}
_processParams(obj: any) {
/* Convert this
{ age: [1,2,3] }
To:
param.append('age', 1);
param.append('age', 2);
param.append('age', 3);
*/
let params = new URLSearchParams();
for (let key in obj) {
for (let index in obj[key] ) {
params.append(key, obj[key][index]);
}
}
return {
search: params
};
}
Super simple answer/example:
// Create:
const params = new URLSearchParams({
a: 1,
b: 2
})
// OR
// const params = new URLSearchParams("a=1&b=2")
// Append
params.append('c', 'woohoo') // Note: if c param already exists in params, this will replace it (won't be adding new param if already exists, hence no duplications)
console.log(params.toString())
// Prints: 'a=1&b=2&c=woohoo'
Here is my approach. We have a simple requirement where the object is only a key value pair where the value might be a string or an array. We haven't found a use case for nested objects.
So let's say we want to convert this object into a query string or vice versa:
const input = {
ini: 'ini',
itu: 'itu',
ayo: ['desc', 'asc'],
}
Then we have two functions to parse & stringify:
function stringify(input) {
const params = new URLSearchParams();
for (const key in input) {
if (Array.isArray(input[key])) {
input[key].forEach(val => {
params.append(key + '[]', val)
})
} else {
params.append(key, input[key]);
}
}
return '?' + params.toString();
}
function parse(input) {
const payload = {};
const params = new URLSearchParams(input);
for(let [key, val] of params.entries()) {
if (key.endsWith('[]')) {
key = key.replace(/\[\]$/, '');
if (payload[key]) {
payload[key].push(val);
} else {
payload[key] = [val]
}
} else {
payload[key] = val;
}
}
return payload;
}
So the result should be "?ini=ini&itu=itu&ayo%5B%5D=desc&ayo%5B%5D=asc". This is similar to the array format that is found in this example.
Please note that this might not be battle tested, but for us we don't really have complicated object structure.
const url = new URL('/', location.origin);
console.log(url.href); // https://stackoverflow.com/
Object.entries({this:4,that:1}).forEach((item)=>{
// note .set replaces while .append will duplicate params
url.searchParams.append(...item);
});
console.log(url.href); // https://stackoverflow.com/?this=4&that=1

Categories