I want to remove double quotes from a variable - javascript

var aProd = "{'name':'Product One','description':'Description Product One','unit_amount':{'currency_code':'USD','value':'247','sku':'h545'},'quantity':'1'}";
var item = new Array(aProd);
console.log(item);
result this
[
"{'name':'Product One','description':'Description Product One','unit_amount':{'currency_code':'USD','value':'247','sku':'h545'},'quantity':'1'}"
]
How remove double quotes?
to this
[
{'name':'Product One','description':'Description Product One','unit_amount':{'currency_code':'USD','value':'247','sku':'h545'},'quantity':'1'}
]
already tried
var item = new Array(String(ci).replace(/"/g, ""));
or
var item = ci.toString().replace(/"/g, "");
but I can't remove double quotes

Use JSON.parse (after converting all single quotes to double quotes):
let aProd = "{'name':'Product One','description':'Description Product One','unit_amount':{'currency_code':'USD','value':'247','sku':'h545'},'quantity':'1'}";
let res = [JSON.parse(aProd.replaceAll("'", '"'))];
console.log(res);

It sounds like you want to create an array with that data as its first object. Now, the data isn't valid JSON so you need to replace all the single quotes with double quotes first, parse it, and then wrap it in [] braces.
const aProd = "{'name':'Product One','description':'Description Product One','unit_amount':{'currency_code':'USD','value':'247','sku':'h545'},'quantity':'1'}";
// Replace the single quotes with double quotes
const json = aProd.replaceAll("'", '"');
// Parse the now-valid JSON, and place it in an array
const arr = [JSON.parse(json)];
// Here's your new data structure
console.log(arr);
// And here, and an example, we log the value
// of `name` from the object which is the
// first `[0]` element of the array
console.log(arr[0].name);

Related

How to convert comma separated strings enclosed within bracket to array in Javascript?

How to convert below string to array in Javascript? The reason is that I want to take both value separately.
The string is value from an element, when I print it to console I got:('UYHN7687YTF09IIK762220G6','Second')
var data = elm.value;
console.log(data);
You can achieve this with regex, like this for example :
const string = "('UYHN7687YTF09IIK762220G6','Second')";
const regex = /'(.*?)'/ig
// Long way
const array = [];
let match;
while (match = regex.exec(string)){
array.push(match[1]);
};
console.log(array)
// Fast way
console.log([...string.matchAll(regex)].map(i => i[1]))
source
let given_string = "('UYHN7687YTF09IIK762220G6','Second')";
// first remove the both ()
given_string = given_string.substring(1); // remove (
given_string = given_string.substring(0, given_string.length - 1); // remove )
let expected_array = given_string.split(',');
console.log(expected_array);

Array values to a string in loop

I have an object (key value pair) looks like this
I want to get a string of '[100000025]/[100000013]'
I can't use var str = OBJ[0].PC + OBJ[1].PC (which gives me '100000025100000013')
because I need the bracket structure.
The number of items can vary.
Added >> Can it be done without using arrow function?
const string = array.map(({PC}) => `[${PC}]`).join('/')
You could map every string to the string wrapped in brackets, then join that by slashes.
You can use a map() and a join() to get that structure. - this is hte same solution as Puwka's = but without the template literal.
var data = [
{am: 1, ct: "", pc: "1000000025"},
{am: 2, ct: "", pc: "1000000013"}
];
let newArr = data.map(item => "[" + item.pc +"]");
console.log(newArr.join("/")); // gives [1000000025]/[1000000013]
You can always use classic for in loop
let arr = [{PC:'1000'},{PC:'10000'}]
let arrOut = [];
for(let i = 0; i < arr.length; i++) {
arrOut.push('[' + arr[i].PC + ']');
}
now the arrOut is equal ["[1000]", "[10000]"] what we need is to convert it to a string and add '/' between items.
let str = arrOut.join('/');
console.log(str) // "[1000]/[10000]"
So you need a string in the format of: xxxx/yyyyy from a complex object array.
const basedata = [...];
const result = basedata.map( item => `[${item.PC}]` ).join('/')
so i will explain it now. The map function will return a new array with 1 entry per item. I state that I want PC, but i added some flavor using ticks to inject it inbetween some brackets. At this point it looks like: ["[1000000025]","[100000013]"] and then join will join the arrays on a slash, so it will turn into an array.
"[100000025]/[100000013]"
Now, this will expand based on the items in your basedata. So if you have 3 items in your basedata array, it would return:
"[10000000025]/[100000013]/[10000888]"
First if you want to divide the result then it will be better to change it into number and then just do the division.
Example
Number.parseInt("100000025")/Number.parseInt("100000013")
If you want to display it then better to use string interpolation
surround it with back tick
[${[0].PC}]/[${[1].PC}]
Hope this is what are you looking for

A nested array of string to number

I'm looking to convert a nested array of the type string to type float, or alternatively parsing it from a text file. Format is something along the lines of this [45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]
The first step would be to create valid JSON from your string.
If your input will always follow the schema you showed us, you could just prepend and append brackets to the string. This is not a pretty solution though. You should first check if you can get valid JSON in the first place.
A solution could look like this, provided that the input string will always follow the format of "[float, float], [float, float]":
const input = "[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]";
// Add brackets in order to have valid JSON.
const arrayString = "[" + input + "]";
// Parse the string into an object.
const parsedArray = JSON.parse(arrayString);
// Flatten the nested array to get a one dimensional array of all values.
var flattenedArrays = [].concat.apply([], parsedArray);
// Do something with your values.
flattenedArrays.forEach(floatValue => console.log(floatValue));
You can use JSON.parse, if your numbers are actually numbers in a JSON (serialized without quotes).
let test = "[[3, 4.2], [5, 6]]";
let test2 = JSON.parse(test);
console.log(test2);
Otherwise you can simply convert your array of array of strings to array of array of numbers using + and some array mapping. :
let test = [["3", "4.2"], ["5", "6"]];
let test2 = test.map((x) => x.map((y) => +y));
console.log(test2);
Of course, you can combine both solutions if for some reason you don't control the input and have a JSON containing strings.
This thread shows you how to loop through an array of strings to convert it to an array of floats.
i hope this will work..
var input = [[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]]
var output = [];
input.forEach(o => {
o.forEach(s => parseFloat(s))
output.push(o);
})
console.log(output);

How to Convert key/value pair String to a JSON object?

How can I covert key=value pair string to json object
input :
test = one
testTwo = two
Output should be json object
"test":"one","testTwo":"two"
Is input a string? You could first split it by \n to get an array of key/value-pairs, and then split each pair by =, to get an array of the key and the value.
var input = `test = one
testTwo = two
testThree = three
testFour = four`;
var output = input.split('\n').reduce(function(o,pair) {
pair = pair.split(' = ');
return o[pair[0]] = pair[1], o;
}, {});
console.log(output);
The safest way to do it is JSON.parse(string)

Using JavaScript's split to chop up a string and put it in two arrays

I can use JavaScript's split to put a comma-separated list of items in an array:
var mystring = "a,b,c,d,e";
var myarray = mystring.split(",");
What I have in mind is a little more complicated. I have this dictionary-esque string:
myvalue=0;othervalue=1;anothervalue=0;
How do I split this so that the keys end up in one array and the values end up in another array?
Something like this:
var str = "myvalue=0;othervalue=1;anothervalue=0;"
var keys = [], values = [];
str.replace(/([^=;]+)=([^;]*)/g, function (str, key, value) {
keys.push(key);
values.push(value);
});
// keys contains ["myvalue", "othervalue", "anothervalue"]
// values contains ["0", "1", "0"]
Give a look to this article:
Search and Don't Replace
I'd still use string split, then write a method that takes in a string of the form "variable=value" and splits that on '=', returning a Map with the pair.
Split twice. First split on ';' to get an array of key value pairs. Then you could use split again on '=' for each of the key value pairs to get the key and the value separately.
You just need to split by ';' and loop through and split by '='.
var keys = new Array();
var values = new Array();
var str = 'myvalue=0;othervalue=1;anothervalue=0;';
var items = str.split(';');
for(var i=0;i<items.length;i++){
var spl = items[i].split('=');
keys.push(spl[0]);
values.push(spl[1]);
}
You need to account for that trailing ';' though at the end of the string. You will have an empty item at the end of that first array every time.

Categories

Resources