Looping through a text file in React or JS - javascript

I'm getting a text file as API response from here https://api.pwnedpasswords.com/range/D0597 that looks like this
007F24D71AC210875C58951F5D99ACC71D2:3
0097880A0B749B59A5F7FD0D943A133ADE1:4
00CAEC74DE2FA10428E6D3FAD065D53B865:4
00F8C45A33243D0A4FD293DC70130E82E00:1
024556F4CB4A1DA178A6EC4E43ECED22467:1
030BA417A72B878EC629BD585705D306260:1
03664676C5A123BE6927DB6BAC5F5427468:1
0491953CF08D183806C28DB827835D27348:1
04BA7B823BBB772A8172F94A757AAF59A39:2
04D3C208B89E12C60AB12900690E86C13DA:1
06856BA40BCB6BCE13C40F271487F347BA5:1
071E3D06232DEA85E297102F6037164C033:5
and I need to loop through and check if the value of an input is included in the list of first item. If present I need to show the second value after ":".
I was trying to use split() for new line and ":" and iterate but kind of got lost.

// data is your text file
var foo = data.split("\n"),
bar = "your input";
Object.keys(foo).forEach(function(key) {
if (foo[key].split(":")[0] === bar) {
console.log(foo[key].split(":")[1]);
}
});

Related

Replace particular file content in nodejs

I want to replace a particular line using javascript with new content.
This is the file content,
SERVER=1055#localhost
GROUP_SERVERS=2325#localhost
LINE_IAM_INTERESTED=KTYUIERVW:2800
FILE_PATH="C:\Program Files\somefile\Shared Files\"
In this line, LINE_IAM_INTERESTED=KTYUIERVW:2800 .I want to replace KTYUIERVW with KJHTERDY and 2800 with 78945
I have shown what I tried using fs appendfilesync
fs.appendFileSync('file_name').toString().split('\n').forEach(function(line){
app.console.log("called append");
var sEntry = line.split("=");
if (sEntry.length == 2) {
if (sEntry[0] == "LINE_IAM_INTERESTED") {
app.console.log("found one!!!!");
}
}
});
you can try READ -> REPLACE -> WRITE flow:
fs.writeFileSync('file_name', fs.readFileSync('file_name').replace('KTYUIERVW:2800', 'KJHTERDY:78945'))
appendFile and appendFileSync are used for adding to the end of the file. Although you can do it as a one liner as shown in the other answer, I've kept the structure of your code the same. Here you want to read the data, modify it then re-write it. Using the block of code you have, you can modify it to use readFileSync and writeFileSync.
let newData = fs.readFileSync('file_name', 'utf-8').split('\n').map(line => {
let sEntry = line.split('=')
if (sEntry.length == 2) {
if (sEntry[0] == "LINE_IAM_INTERESTED") {
console.log("found one!!!!");
return sEntry[0] + '=' + 'KJHTERDY:78945'
}
}
return line
}).join('\n')
fs.writeFileSync('file_name', newData)
I've swapped the forEach for map which lets us change the array data by returning the desired value. The new array is then joined back together and written back to the file.

Show DIV only when url has specific query parameter string jQuery

I am trying to show the hidden div only when the specific url have specific value, like below:
var url = window.location.search;
if (url.match("Test Value")) {
$(".testdiv").show();
}
else if (url.match("Some Text")){
$(".textdiv").show();
}
Not sure if I am trying the correct way and if the none of the string matching, its showing error, what appproach should I try here?
You can use URL.searchParams.
new URL(location).searchParams.get('nameOfQueryStringParam')
Example:
const param = new URL('http://example.com?x=1&y=2').searchParams
console.log(param.get('x')) // 1
console.log(param.get('y')) // 2
console.log(param.get('z')) // null
Then, use it for your purpose like ..
param.get('x') ? $('#div1').show() : $('#div2').show()

How to get value in Js of other field that is passed to widget? Odoo

I created a widget which fills some fields automatically. Basically I am checking some values from google maps geolocate and filling other fields depending on what those values are. Turned out I need to check one value that is already in my form. What happens at the moment I get only value that was saved before and if it changes I still get the old value. My question if how to get that value real-time?
My code is something like this:
var gmap_autocomplete = form_common.AbstractField.extend({
// functions such as start, init, on_ready...
setFields : function (fieldName, fieldValue) {
var not_vat_payer = this.view.datarecord[this.node.attrs.check_not_vat]);
// Here I get the value that I want of previous form save
// for example if value was true, I came here and triggered this
//widget I will get value true, but if I change it to false
// I will still get true value of previous save
}
});
My field with widget looks like this:
<field name="not_vat2"/>
<field name="autocomplete" class="autoc" widget="gmap_autocomplete" street="street"
city="city" zip="zip" country_id="country_id" lang="lang" invoice_lang="invoice_lang"
property_account_payable_id="property_account_payable_id"
property_account_receivable_id="property_account_receivable_id"
check_not_vat="not_vat2"/>
Found the solution which is really simple:
This will return field value which is in view no matter its stored in db or not.
this.field_manager.get_field_value('field_name');
exmple.js
Make changes something like..
var model_obj = new Model('model.name');
var gmap_autocomplete = form_common.AbstractField.extend({
// functions such as start, init, on_ready...
setFields : function (fieldName, fieldValue) {
var not_vat_payer = this.view.datarecord[this.node.attrs.check_not_vat]);
new_val = false;
model_obj.call('method_name',[new_val]).then(function(result){});
}
});
example.py
#api.model
def method_name(self,new_val):
//write code for change field value

Updating multiple dropdowns with json data

What is good practice when storing an HTML select dropdown into a JavaScript variable. I also need to capture the value which they selected and pass that through.
I originally tried to use jQuery to create the option and hold it in a variable but it would error out.
var keyNamesList = $('<option></option>').val('').html('Select a Key');
I then used an HTML string and appended the options list in a loop with with more HTML represented as a string. See JSFIDDLE link for a mock up.
var keyNamesList = "<option value = ''> Select an item</option>"
keyNamesList += "<option value = '"+data.key+"'>" + data.value + "</option>";
JSFIDDLE
$('<option></option>')...
Should just be $('option').
PS: What are you trying to do?
It's unlikely that using an append per option and setting the value and content via the DOM API is going to cause a big performance hit, but just as general rule it's considered good practice to avoid multiple append and DOM mutation calls if you can, so I would normally build a single HTML string:
function getOptions(data, blank) {
var optTpl = '<option value="%key%">%label%</option>',
options = [];
if (blank) {
// if blank is truthy then append an option - if bool true then
// a default label, otherwise use the value of blank as label
options.push(optTpl
.replace('%key%','')
.replace('%label%', (blank === true ? 'Select one...' : blank))
);
}
$.each(data, function (i, datum){
options.push(optTpl
.replace('%key%',datum.key)
.replace('%label%', datum.value)
);
});
return options.join('');
}
// usage:
$('theSelectElement').append(getOptions(data, 'Select something!'));
I like to use a kind of template and call string replacements but you could build the strings on each iteration like you proposed in your question:
options.push("<option value = '"+data.key+"'>" + data.value + "</option>");
Example un-integrated with yours: http://jsfiddle.net/8tjwL6u5/

Prettify json data in textarea input

I've searched for this particular topic and couldn't find anything similar to it. If there is please close this and give a link.
I'm creating a json data api simulator. I want users to be able to copy and paste a json object request into a textarea where they can also modify it before sending it to the server.
Problem is json obj copy and patses often results in extra spaces and is never aligned properly, even with the pre tag. I also want a good color scheme applied to keys and values.
I've seen plugins, other questions and snippets of code, but they don't apply to textareas where the text is editable. Is there to keep it styled while in edit mode without it showing all the html tags that styled it? I want to be able to write it from scratch with javascript or jquery.
The syntax highlighting is tough but check out this fiddle for pretty printing a json object entered in a text area. Do note that the JSON has to be valid for this to work. (Use the dev console to catch errors.) Check jsLint for valid json.
The HTML:
<textarea id="myTextArea" cols=50 rows=10></textarea>
<button onclick="prettyPrint()">Pretty Print</button>
The js:
function prettyPrint() {
var ugly = document.getElementById('myTextArea').value;
var obj = JSON.parse(ugly);
var pretty = JSON.stringify(obj, undefined, 4);
document.getElementById('myTextArea').value = pretty;
}
First try simple input like: {"a":"hello","b":123}
Simple pretty printing of JSON can be done rather easily. Try this js code: (jsFiddle here)
// arbitrary js object:
var myJsObj = {a:'foo', 'b':'bar', c:[false,2,null, 'null']};
// using JSON.stringify pretty print capability:
var str = JSON.stringify(myJsObj, undefined, 4);
// display pretty printed object in text area:
document.getElementById('myTextArea').innerHTML = str;
For this HTML:
<textarea id="myTextArea" cols=50 rows=25></textarea>
And check out JSON.stringify documentation.
Late answer but modern one, use the secret intendation parameter.
I usually go for:
JSON.stringify(myData, null, 4);
Here's the code definition, it explains it well.
stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* #param value A JavaScript value, usually an object or array, to be converted.
* #param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified.
* #param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
For the parsing step you're just going to want to JSON.parse the contents of the textarea and handle any errors from bad input.
For the formatting part of your question, Use JSON.stringify(blob, undefined, 2). Alternatively, if you need colors here is a simple JSON format/color component written in React:
const HighlightedJSON = ({ json }: Object) => {
const highlightedJSON = jsonObj =>
Object.keys(jsonObj).map(key => {
const value = jsonObj[key];
let valueType = typeof value;
const isSimpleValue =
["string", "number", "boolean"].includes(valueType) || !value;
if (isSimpleValue && valueType === "object") {
valueType = "null";
}
return (
<div key={key} className="line">
<span className="key">{key}:</span>
{isSimpleValue ? (
<span className={valueType}>{`${value}`}</span>
) : (
highlightedJSON(value)
)}
</div>
);
});
return <div className="json">{highlightedJSON(json)}</div>;
};
See it working in this CodePen:
https://codepen.io/benshope/pen/BxVpjo
Hope that helps!
If you are a jquery fan, you can also use this small plugin I wrote:
// The plugin
$.fn.json_beautify= function() {
this.each(function(){
var el = $(this),
obj = JSON.parse(el.val()),
pretty = JSON.stringify(obj, undefined, 4);
el.val(pretty);
});
};
// Then use it like this on any textarea
$('textarea').json_beautify();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="myTextArea" cols=50 rows=5>{"name":"John","age":30}</textarea>
<textarea id="myTextArea2" cols=50 rows=5>{"name":"Bob","age":55}</textarea>
UPD
Changed code to multiselected elements.
I don't think that can be done with regular textareas. What you can do (and how most online code editors do it) is to create a transparent textarea that overlays on top of a div that contains the styled code. The user would still be able to type and interact with the input (and it fires the associated form events), and you can show syntax highlighting in the div that the user will visually see
(see Textarea that can do syntax highlighting on the fly?)
Now as for JSON formatting, I would add custom events to the textarea so that when a user types or paste something, run it through a Javascript JSON prettifier (see How can I pretty-print JSON using JavaScript?) and then re-populate the div and textarea accordingly
Here's a recursive function to return an object if it has been stringified multiple times:
const jsonPrettify = (json) => {
if (typeof json === 'object' && json !== null) {
const pretty = JSON.stringify(json, undefined, 4);
return pretty;
}
try {
const obj = JSON.parse(json);
return jsonPrettify(obj);
} catch (e) {
return json;
}
};

Categories

Resources