function returnsSomething(data1, data2) {
let error = null;
let something = {
varA = data1 ? data1 : error += 'varA';
varB = data2 ? data2 : error += 'varB';
}
return {
status: error ? false : true;
returnedData: error ? error += 'not available' : something
}
}
function callsThePreviousFunction() {
let data1 = {
a: something1,
b: something2
}
let data2 = {
a: something3,
b: something4
}
let storeData = returnsSomething(data1, data2)
if(storeData.status){
return storeData.returnedData;
}else{
return false
}
}
I believe the function returnsSomething can be written in a better way to return the data and return the stored errors based on the conditions. Any help will be highly appreciated. THANK YOU
Related
For some reason I have variables outside of my function and I'm updating that variable in my function but when I call that variable in another function I get a undefined typeError
let bikeShare = []
let stations = []
function startRide(vin) {
bikeShare = bikeShare.map((bike) => {
bike.vin === vin ? { ...bike, checkOut: true } : bike
})
return {}
}
function endRide(vin) {
console.log(bikeShare)
bikeShare = bikeShare.map((bike) => {
bike.vin === vin && bike.checkOut
? { ...bike, checkOut: false, totalRides: bike.totalRides + 1 }
: bike
})
return {}
}
function createBike(color = 'red') {
const vin = bikeShare.length + Date.now();
const payload = { vin, color, checkOut: false, totalRides: 0 }
bikeShare.push(payload);
return payload
}
const bike_1 = createBike('red')
const bike_2 = createBike('blue')
const bike_7 = createBike('green')
startRide(bike_1.vin) // in the startRide function I get an array [undefined, undefined, undefined]
endRide(bike_1.vin)
You are in the startRide() function not returning the result of each assignment in the .map method, so it returns undefined which why you see the array of undefined values.
This should fix it:
let bikeShare = []
let stations = []
function startRide(vin) {
bikeShare = bikeShare.map((bike) => {
return bike.vin === vin ? { ...bike, checkOut: true } : bike
})
return {}
}
function endRide(vin) {
console.log(bikeShare)
bikeShare = bikeShare.map((bike) => {
bike.vin === vin && bike.checkOut
? { ...bike, checkOut: false, totalRides: bike.totalRides + 1 }
: bike
})
return {}
}
function createBike(color = 'red') {
const vin = bikeShare.length + Date.now();
const payload = { vin, color, checkOut: false, totalRides: 0 }
bikeShare.push(payload);
return payload
}
const bike_1 = createBike('red')
const bike_2 = createBike('blue');
const bike_7 = createBike('green');
startRide(bike_1.vin) // in the startRide function I get an array [undefined, undefined, undefined]
endRide(bike_1.vin)
To lift this out of comment, the body of the map argument function in startRide is enclosed in curly braces. You could remove the braces or put return bike inside the braces to stop it returning undefined.
However, setting bike.vin to a bike "payload" object with checkout set to true, leaving bike.checkout set to false, is a bug. One solution might be to use find instead of map:
let bikeShare = []
let stations = []
function startRide(vin, start = true) {
const bike = bikeShare.find(bike=>bike.vin === vin);
if( bike) {
bike.checkOut = start;
}
return bike; // for debugging
}
function endRide(vin) {
return startRide( vin, false);
}
function createBike(color = 'red') {
const vin = bikeShare.length + Date.now();
const payload = { vin, color, checkOut: false, totalRides: 0 }
bikeShare.push(payload);
return payload
}
const bike_1 = createBike('red')
const bike_2 = createBike('blue')
const bike_7 = createBike('green')
console.log( startRide(bike_1.vin));
console.log( endRide(bike_1.vin));
how to find the json path for a specific value using javascript
var data = {
key1: {
children: {
key2:'value',
key3:'value',
key4: value
},
key5: 'value'
}
expected result from the above data.key1.children.key3
Any help would be appreciated.
var str = "key3";
data["key1"]["children"][str];
This function returns all available paths in your(any) object:
Using this function you can get
["key1.children.key2", "key1.children.key3", "key1.children.key4", "key1.key5"]
function allPaths(root) {
let stack = [];
let result = [];
// checks if object
const isObject = value => typeof value === "object";
stack.push(root);
while (stack.length > 0) {
let node = stack.pop();
if (isObject(node)) {
Object.entries(node).forEach(([childNodeKey, childNodeValue]) => {
if (isObject(childNodeValue)) {
const newObject = Object.fromEntries(
Object.entries(childNodeValue).map(([cnk, cnv]) => {
return [`${childNodeKey}.${cnk}`, cnv];
})
);
stack.push(newObject);
} else {
stack.push(`${childNodeKey}`);
}
})
} else {
result.push(node);
}
}
return result.reverse();
}
Let me know in the comments if it was helpful for you
Object.keys(data).forEach((key) => {
bannerData[key] = data[key][0];
console.log(key);
if (key == "timestamp") {
labels.push(data[key]);
console.log("wtf");
console.log(labels);
} else {
datasets.push(data[key]);
}
});
generates
exhaust_humidity
exhaust_temperature
intake_humidity
intake_temperature
lights
relay
room_humidity
room_temperature
soil_moisture_1
soil_moisture_2
soil_moisture_3
soil_moisture_4
soil_moisture_5
soil_moisture_6
soil_moisture_7
soil_moisture_8
timestamp
the console.log("wtf"); is never called, because the last key never registers as equal to "timestamp".
Not sure what I'm missing.
const data = {
not_timestamp: 1,
timestamp: 2,
}
const bannerData = {}
const datasets = []
const labels = []
Object.keys(data).forEach((key) => {
bannerData[key] = data[key][0];
console.log(key);
if (key == "timestamp") {
labels.push(data[key]);
console.log("wtf");
console.log(labels);
} else {
datasets.push(data[key]);
}
});
Works fine. If I had to guess, labels is undefined in your script, causing it to error before "wtf" is printed.
So in below code if i pass ancillaryProductInd as boolean code works, but when I pass it as a string, it does not work. In my understanding the below code should only work when I pass "false" string value and throw error on boolean. Any idea what is the issue here ?
main.ts
request
var rxInfos = [{
"ancillaryProductInd": "false",
"indexID": "eyJrZXkiOiIEOHdpNUpNWmR3PT0ifQ=="
}]
function subQuestionsHandler(rxInfos, data) {
const subQuestionArray = [];
rxInfos.forEach((rxInfo) => {
const subQuestion = {
question: []
};
if (rxInfo.ancillaryProductInd !== undefined && rxInfo.ancillaryProductInd === "false") {
subQuestion.question = data;
subQuestionArray.push(subQuestion);
}
});
return subQuestionArray;
}
subQuestionsHandler(rxInfos, [{
some data
}]);
Your example code works as expected with a string value "false" and doesnt run the if block when a boolean is used. See my example:
var rxInfos = [
{
ancillaryProductInd: "false",
indexID: "eyJrZXkiOiIEOHdpNUpNWmR3PT0ifQ=="
},
{
ancillaryProductInd: false,
indexID: "eyJrZXkiOiIEOHdpNUpNWmR3PT0ifQ=="
}
];
function subQuestionsHandler(rxInfos, data) {
const subQuestionArray = [];
rxInfos.forEach(rxInfo => {
const subQuestion = {
question: []
};
if (
rxInfo.ancillaryProductInd !== undefined &&
rxInfo.ancillaryProductInd === "false"
) {
console.log("no error");
subQuestion.question = data;
subQuestionArray.push(subQuestion);
} else {
console.log("throw error");
}
});
return subQuestionArray;
}
subQuestionsHandler(rxInfos, [
{
test: ""
}
]);
var storage = chrome.storage.local;
var cachedStorage = {};
this is js file.It shows unexpected token u.even though I've done parsing correctly.and it also shows unexpected token for for its html source page.can any one suggest me how to sort this out.
var defaultStorage = [{
savedPatterns: JSON.stringify([
[{
"en": "English"
}, {
"it": "Italian"
}, "25", true],
[{
"en": "English"
}, {
"la": "Latin"
}, "15", false]
]),
}];
error occurs here unexpected token u
function createPattern() {
console.log('createPattern begin');
var patterns = JSON.parse(S('savedPatterns'));
var srce = [],
trg = [],
prb = [];
console.log(S('savedPatterns'));
console.debug(S('savedPatterns'));
var translator = document.getElementById('translatorService');
var service = translator.children[translator.selectedIndex].value;
srce[0] = document.getElementById('sourceLanguage');
srce[1] = srce[0].children[srce[0].selectedIndex].value;
srce[2] = srce[0].children[srce[0].selectedIndex].text;
trg[0] = document.getElementById('targetLanguage');
trg[1] = trg[0].children[trg[0].selectedIndex].value;
trg[2] = trg[0].children[trg[0].selectedIndex].text;
prb[0] = document.getElementById('translationProbability');
prb[1] = prb[0].children[prb[0].selectedIndex].value;
patterns.push([
[srce[1], srce[2]],
[trg[1], trg[2]],
prb[1],
false,
service
]);
saveBulk({
'savedPatterns': JSON.stringify(patterns)
}, 'Saved Pattern');
console.log('createPattern end');
}
function S(key) {
return cachedStorage[key];
}
function loadStorageAndUpdate(callback) {
storage.get(null, function(data) {
console.log('data: ' + data + ' : ' + JSON.stringify(data));
var d = {};
if (!data || JSON.stringify(data) == '{}') { // in this case, storage was not initialized yet
console.log('setting storage to defaultStorage (stringified): ');
console.log(JSON.stringify(defaultStorage));
storage.set(defaultStorage);
d = defaultStorage;
} else {
d = data;
}
cachedStorage = d;
if (!!callback) {
callback(d);
}
});
}
Error Unexpected token comes when JSON.parse fails and depending on character (u in this case), you can assume its cause.
u is if value is undefined
o is if value is object
try {
JSON.parse(undefined)
} catch (ex) {
document.write(ex.message + "<br/>")
}
try {
JSON.parse({})
} catch (ex) {
document.write(ex.message)
}
You can try something like this:
function s(key) {
var obj = {
foo: "foo",
bar: "bar"
}
var v = null;
try {
v = JSON.parse(obj[key]);
} catch () {
v = obj[key];
}
return v;
}
function main() {
var v = s("foo");
}
Please refer following post for more information. Uncaught SyntaxError: Unexpected token with JSON.parse
You're trying to parse undefined. When you call JSON.parse(), you're passing in S('savedPatterns'), which in turn tries to access cachedStorage['savedPatterns'], but that starts as undefined, which you can't parse. You could just initialize your cachedStorage as:
var cachedStorage = {
savedPatterns: JSON.stringify([])
};