How to convert a string look like an array [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I make a get request to URL "http://cafef3.mediacdn.vn/v2/kby/ccf4d584-4b06-4370-acff-c0241b4ad0d6/kby.js". It is a javascript file and I get a string "var oc=[object_1, object_2]".
How can I create a new array based on the string above? e.g. let newArray = [object_1, object_2]
Thank!

Assuming it's for browser.. you could create a new script tag (so that the content of the javascript file will be parsed) and then assign the new variable from there.
Here is some code for reference:
const newScriptTag = document.createElement('script')
newScriptTag.textContent = content; // content is the value of the js file (var oc... )
document.body.append(newScriptTag)
let newArray = oc;
// then remove the script tag
document.body.removeChild(scriptTag)

Well, you could get rid go the prefix and suffix of your string using something like:
let result = 'var oc=["object_1", "object_2"];';
result = result.replace('var oc=','');//to remove the variable definition from the start
result = result.slice(0,-1);//to remove ';' at the end. You can use this, because strings are arrays of characters
And then use:
result = JSON.parse(result);//this should give you a nice array with your objects in it
You can find references for the methods I mentioned from a couple of different sources:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
https://www.w3schools.com/jsref/jsref_replace.asp
https://www.w3schools.com/jsref/jsref_slice_array.asp
EDIT:
That last part with JSON.parse() would work if the return for your request was a valid JSON. but it's not, that's JS code, representing the definition of an object. To parse that, you could use eval(). But you should exercise caution and only use that in strings that return from trustworthy sources, since that could inadvertently execute malicious code inside your code.
That said, the last line of code to solve your problem would be something like:
result = eval(result)
console.log(result);
Thankfully, there's a better way to do it using Function() like so:
result = Function('"use strict";return (' + result + ')')
console.log(result());
You can read the reference from these two last ways of parsing code as string in here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Never_use_eval!

Turn each object into an array using Object.entries and merge the arrays.
const obj1 = { "1": 500, "2": 15, "5": 4, "4": 480, "10": 87 };
const obj2 = { "1": 500, "2": 15, "5": 4, "4": 480, "10": 87 };
const myArray = Object.entries(obj1).concat(Object.entries(obj2));;
console.log(myArray);

Related

Remove all elements in an array that contain a certain character [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
I have a Javascript array var array = ["1-2", "3-6", "4", "1-6", "4"] and want to remove all elements that contain the variable var m = "6", i.e. "3-6" and "1-6".
I found this line of code var newarray = array.filter(a => a !== "4"), which creates a new array that does not contain the two "4" elements. But I have not found out how to use regular expressions in order to remove all elements that CONTAIN the given variable m = "6".
I thought about something like var newarray = array.filter(a => a !== /eval("return m")/), but this does not work.
I very appreciate your help and apologize for my English :)
string.includes()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
const array = ["1-2", "3-6", "4", "1-6", "4"];
const newarray = array.filter(a => !a.includes("6"))
console.log(newarray);
regex alternative
if you need complex pattern checking, the regex is the way to go.
const array = ["1-2", "3-6", "4", "1-6", "4"];
const newarray = array.filter(a => !a.match(/6/gi))
console.log(newarray);
For example, checking uppercase and lowercase simultaneously, or multiple letters only with [abcde] or some numbers [678] etc...
without nested includes() or logic with if/else.
for learning regex you can use this https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#regular-expressions
another info:
with regex I suggest to add also the g at the end just in case /6/g
g means global (but in this case isn't important, because if there are 6 at least one time. this code will work fine (if you care about multiple 6 then use g)
also use i if you want to select also texts
in fact without i: "A" and "a" aren't the same
so with i you don't have to worry about UPPERCASE or lowercase
you can use both them by doing like this /6/gi

Convert JSON to java script [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Can anybody provide the java script for the below JSON. I tried in many way, but could not add the field "set"
{
"student":[
"set",
[
{
"name":"abcd",
"id":"1234"
}
]
]
}
So your javaScript variable would be an objecthaving property/key name student of array type. Now student has two elements set a string and an object, other element is also an array, has an element of object type. This element has two properties/keys name and id.
var required = {};
required.student = [];
required.student.push("set");
var innerArray = [];
var innerObj = {};
innerObj.name = "abcd";
innerObj.id = "1234";
innerArray.push(innerObj);
required.student.push(innerArray);
document.write('<pre> ' + JSON.stringify(required,0, 3) + '</pre>');
JSON.parse(jsonString);
Is a pure JavaScript approach so long as you can require a reasonably modern browser.
See also https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I'm not sure what you are trying to do, but...
If you just want to have the JSON object you described available in your JavaScript code, you can just put it into a variable.
var json = {
"student":[
"set",
[
{
"name":"abcd",
"id":"1234"
}
]
]
};
// Testing the object:
// Print the JSON object we made, as a string
console.log(JSON.stringify(json));
// Print the first item inside the 'student' array
console.log(json.student[0]);
If you instead have your JSON as a string, you can parse it to JSON object with:
var json = JSON.parse(jsonString);

How to access elements of json array using javascript/jquery? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a json array like this
AlreadySaved:[
{
"SNO":1,
"SNUMBER":"827",
"STARTDATE":"11/12/2016",
"STARTTIME":"03:06:50 PM",
"ITEMNAME":"KBand",
"ITEMCODE":"KB2541",
"ITEMSKUNAME":"Band",
"ITEMSKUCODE":"BT102",
"SALESRATE":100.0,
"PURCHASERATE":5.0,
"DOE":"~",
"STOCKQTY":2.0,
"PHYSICALQTY":1.0
}
]
I need to fetch value of PHYSICALQTY and display it in alert.I am new to jquery/javascript so any help would be appreciated.
You can access json like normal objects in js via dot notation.
var json = {"STOCKQTY":2.0,"PHYSICALQTY":1.0};
console.log(json.PHYSICALQTY);
If you Have saved this json under another object You need to go deeper, eg.
var response = {AlreadySaved: [{"STOCKQTY":2.0,"PHYSICALQTY":1.0}] };
console.log(response.AlreadySaved[0].PHYSICALQTY);
Please remember also that in some cases You may have json (eg from response) as string not object.
console.log(typeof someJson); //string
In that cases You need to parse this string into json
var json = JSON.parse(someJsonAsString);
Happy hacking!
You can use json[0].PHYSICALQTY
var json = [{
"SNO": 1,
"SNUMBER": "827",
"STARTDATE": "11/12/2016",
"STARTTIME": "03:06:50 PM",
"ITEMNAME": "KBand",
"ITEMCODE": "KB2541",
"ITEMSKUNAME": "Band",
"ITEMSKUCODE": "BT102",
"SALESRATE": 100.0,
"PURCHASERATE": 5.0,
"DOE": "~",
"STOCKQTY": 2.0,
"PHYSICALQTY": 1.0
}];
document.getElementById('id1').innerHTML=json[0].PHYSICALQTY;
<div>
PHYSICALQTY:<label id="id1"></label>
</div>
You can parse this and then get the value. Ouf course if you receive this like a string.
var a = '[{"SNO":1,"SNUMBER":"827","STARTDATE":"11/12/2016","STARTTIME":"03:06:50 PM","ITEMNAME":"KBand","ITEMCODE":"KB2541","ITEMSKUNAME":"Band","ITEMSKUCODE":"BT102","SALESRATE":100.0,"PURCHASERATE":5.0,"DOE":"~","STOCKQTY":2.0,"PHYSICALQTY":1.0}]'
var output = JSON.parse(a)
console.log(output[0].PHYSICALQTY)
Your JSON object is not valid, you can check that at http://jsonlint.com/
Once you set it to something like
var AlreadySaved =[{"SNO":1,"SNUMBER":"827","STARTDATE":"11/12/2016","STARTTIME":"03:06:50 PM","ITEMNAME":"KBand","ITEMCODE":"KB2541","ITEMSKUNAME":"Band","ITEMSKUCODE":"BT102","SALESRATE":100.0,"PURCHASERATE":5.0,"DOE":"~","STOCKQTY":2.0,"PHYSICALQTY":1.0}] ;
you can access it via AlreadySaved[0]["PHYSICALQTY"]
It is not json object.
Json:
{AlreadySaved:[{"SNO":1,"SNUMBER":"827","STARTDATE":"11/12/2016","STARTTIME":"03:06:50 PM","ITEMNAME":"KBand","ITEMCODE":"KB2541","ITEMSKUNAME":"Band","ITEMSKUCODE":"BT102","SALESRATE":100.0,"PURCHASERATE":5.0,"DOE":"~","STOCKQTY":2.0,"PHYSICALQTY":1.0}]}
In this case you may get your property:
alert(AlreadySaved[0].PHYSICALQTY);
firstly you have to serialize your object like this;
var json_data = JSON.parse(AlreadySaved);
and if you know specific data in json_data, you can call with index number like this;
var result= json_data[0]["PHYSICALQTY"];
Or you can find whatever you want, you can find with foreach;
for(var item in json_data) {
alert(item["PHYSICALQTY"].value);
}
Please try this:
//In case you are getting this from ajax request put "returnObject.Json_Variable" instead of "Json_Variable"
var obj = (JSON.parse("Json_Variable"));
var resultPHYSICALQTY=obj.PHYSICALQTY);

HTML + Alternative of Javascript Switch-Case for simple string & Constant [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
In my Js script, I am using switch case but I dnt want to use it but I am not getting better alternative of this.
Here I am using Js CONSTANT as well for defining First URL & Second URL
var FIRST_URL = "/first_url.html"
var SECOND_URL = "/second_url.html"
& also passing FIRST_URL and SECOND_URL as parameter from function. That's why I used FIRST_URL with double quotes and without quotes.
Snippet :-
if(url == "DIV_ID"){
switch (url_type) {
case FIRST_URL:
case "FIRST_URL":
result = "/first_url.html";
break;
case SECOND_URL:
case "SECOND_URL":
result = "/second_url.html";
break;
default:
result = "other_url.html";
break;
}
}
Suggest something to resolve this.
You can use something like this, but add proper error checking.
Roughtly:
var arr = {};
arr['FIRST'] = 'your first url';
arr['SECOND'] = 'your second url';
result = arr[urlType];
here's an example using object literal:
var arr = {
FIRST : 'your first url',
SECOND: 'your second url'
};
console.log(arr.FIRST)
console.log(arr['SECOND'])
//for adding properties
arr.thr='third prop';
basically the resulting obj is the same to bigmike's answer, but it maybe easier to understand .
This is what is called a key-value pair and the structure is an object (JS definitions).
BTW there is nothing wrong with switch .

converting python code to javascript code [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
can somebody help for my code which is written in python, i want to write it in javascript but im in trouble, i dont know how.
python code
cities={}
for line in open("linnadkaugustega.txt", "r", encoding="UTF-8"):
m=line.strip().split()
abim=[word.split(":") for word in m[1:]]
cities[m[0]]={}
for couple in abim:
cities[m[0]][couple[0]]=int(couple[1])
print(cities);
and i tried in javascript but that doesen't work
function tere(){
console.log("Tere");
$.get('read.txt', function(data) {
cities={};
var lines = (data.trim()).split();
abim=[var word.split(":") for word in m[1:]]
cities[m[0]]={};
for var couple in abim
cities[m[0]][couple[0]]=couple[1];
console.log(cities);
}, 'text');
}
tere();
can somebody help me ?
You have syntax issues translating from python to js. Heres how arrays work...
if you have an array litteral in javascript
var cities = [];
Then we would add to the array by calling push
cities.push('Portland');
...
cities.push('New York');
we can then iterate over the array by calling forEach on the array object.
cities.forEach(function (city, index){
//do work on each city
console.log(city);
});
// Portland
// New York
A few things:
.split() in JS does something different than split in python when no separator is given. To split a line into words, you'll need to split on whitespaces explicitly
you're missing the for loop over the lines of the file. Python uses the iterator syntax for reading from the file, in JavaScript an ajax request loads the whole file and you'll need to split it in lines yourself.
JavaScript does not have that m[1:] syntax, you'll need to use the .slice() method instead
JavaScript does not have array/list comprehensions. You will need to use an explicit loop, or the map method of arrays
your loop syntax is too pythonic. In JavaScript, for loops need parenthesis and an index variable.
So this should do (supposed you have the jQuery library loaded and it finds the file):
$.get('read.txt', function(data) {
var cities = {};
var lines = data.split("\n");
for (var i=0; i<lines.length; i++) {
var line = lines[i];
var m = line.trim().split(/\s+/);
var abim = m.slice(1).map(function(word) {
return word.split(":");
});
var obj = cities[m[0]] = {};
for (var j=0; j<abim.length; j++) {
var couple = abim[j];
obj[couple[0]] = couple[1];
}
}
console.log(cities);
}, 'text');

Categories