How to remove double quotes from json array in javascript - javascript

I have a array :
Var array=[{"name":"May","data1":"1121.0"}]
I want to change it to :
Var array= [{"name":"May","data1":1121.0}]

You can simply check using Number.isNaN with an attempted cast to a number using the + operator. If it returns true then do nothing. If it's false then change the value of the parameter to a cast number.
var array=[{"name":"May","data1":"1121.0"}];
array.forEach(data => {
for(let key in data) Number.isNaN(+data[key]) || (data[key] = +data[key])
});
console.log(array);

Looks like this has been answered before here
I'll summarize;
for(var i = 0; i < objects.length; i++){
var obj = objects[i];
for(var prop in obj){
if(obj.hasOwnProperty(prop) && obj[prop] !== null && !isNaN(obj[prop])){
obj[prop] = +obj[prop];
}
}
}
console.log(JSON.stringify(objects, null, 2));
This does have a bug where 0 becomes null.

You want to convert the value mapped to the "data1" key to be a number instead of a string.
There are many ways to accomplish this in JavaScript, but the best way to do so would be to use Number.parseFloat like so:
var array = [{"name":"May","data1":"1121.0"}];
array[0]["data1"] = Number.parseFloat(array[0]["data1"]);
console.log(array[0]["data1"]); // 1121
If you need to perform this action with multiple objects inside of array, you could do
var array = [{"name":"May","data1":"1121.0"}, {"name":"May","data1":"1532.0"}, etc.] // Note that this is not valid JavaScript
array.map(obj => {obj["data1"] = Number.parseFloat(obj["data1"]); return obj;});

If I understood well, you only want to convert the value of data1, from "1121.0" to 1121.0, in other words from string to number.
To convert only that key (data1), you only need this:
array[0].data1 = parseFloat(array[0].data1)
If that's not what you want, please explain better your question

Related

How can i create an object keys from array values in javascript?

i am new to javascript and while working on a little project i have a problem ,
i have an array which contains the day splitted into quarters like that
['09:00', '09:15', '09:30', '09:45']
i want to create an object with keys that are the values of this array like that :
var obj = {
'09:00': false ,
'09:15': true ,
'09:30': false
....
}
but i don't want to do it manually because the object will contain time until 00:00 so i will have to write a lot of code while i think it is possible to do it automatically ,
i tried fromEntries() method but it gives me a list of key value pairs when i want just to set the keys of the object .
Any solution ?
You can simple use a for-loop like:
const arr = ['09:00', '09:15', '09:30', '09:45'];
let obj = {};
for (var i = 0; i < arr.length; ++i)
obj[arr[i]] = '';
console.log(obj);
I don't know the logic of true and false so i assigned an empty string.
Your intuition was good: Object.fromEntries() does the job.
But you have to build an array like this:
[['09:00',true ], ['09:30', true] /*...*/]
In order to do this, a simple .map() can help
Object.fromEntries(
['09:00', '09:15', '09:30', '09:45'].map(hour=>[hour, true])
)
You can replace true with getStatusFromHour(hour) and then build a function that sets the right boolean to the selected hour.
You can write a simple for loop and append the data to the object with the required state.
Like:
var arr = ['09:00', '09:15', '09:30', '09:45', '10:00'];
var obj = {};
for(var i = 0; i < arr.length; i++) {
obj[arr[i]] = false;
}

How to convert a converted string back into an array?

As far as I know, you can only save strings to local storage. So, I had to write a function so that I could save arrays. If I call console.log(fixA(["string1", [5, [false]], "string2"])); I get an output of "'string1',[5,[false]],'string2'". Here it is:
function fixA(array) {
var toreturn = "";
for (var i = 0; i < array.length; i++) {
if (typeof array[i] === 'object') {
toreturn += "[" + fixA(array[i]) + "]";
} else {
if (typeof array[i] === 'string') {
toreturn += "'" + array[i] + "'";
} else {
toreturn += array[i];
}
}
if (i < array.length - 1) {
toreturn += ",";
}
}
return toreturn;
}
console.log(fixA(["string1", [5, [false]], "string2"]));
The issue now is that I have no clue how to convert it back. I've tried a few things but have always gotten stuck on how I convert the arrays back. This is basically what I've tried:
function fixS(string) {
var toreturn = [];
var temp = string.split(",");
for (var i = 0; i < temp.length; i++) {
// I could run a check here to see if temp[i] starts with "[", but I'm not sure how to tell where the array ends.
// If it is an array, then I'd need to pass everything inside of the array back into fixS, making it recursive.
// The times I tried to do those two things above, I ran into the issue that the commas inside of the sub arrays also split everything, which I don't want (as the recursive function will deal with that).
toreturn.push(temp[i]);
}
return toreturn;
}
console.log(fixS("'string1',[5,[false]],'string2'"));
// This also doesn't return numbers as numbers or booleans as booleans.
Not much there, but it's as far as I've gotten. Any help is appreciated.
Instead of doing your own bespoke solution, unless you have something that can't be represented in JSON (your example can be), use JSON:
On page load:
var data = JSON.parse(localStorage.getItem("data") || "null");
if (!data) {
// There wasn't any, initialize
}
or
var data = JSON.parse(localStorage.getItem("data") || "{}");
...if you want a blank object if there is nothing in local storage.
When saving your data:
localStorage.setItem("data", JSON.stringify(data));
As David said there's JSON.stringify() & JSON.parse();
you can use those methods :
function save_to_storage(id, anything){
localStorage.setItem(id, JSON.stringify(anything));
}
function load_from_storage(id){
return JSON.parse(localStorage.getItem(id));
}
It can be achieved with help of JSON.stringify and JSON.parse functions.
Let me explore with help of code snippet.
var original_arr = ["string1", [5, [false]], "string2"]; // array
// Converting this array into string
var converted_str = JSON.stringify(original_arr); // converted into string
// Converting this string back to array
var new_arr = JSON.parse(converted_str ); // back to array
The other answers have already covered it, but note that P5.js also provides functionality for working, saving, and loading JSON directly.
Take a look at the saveJSON() and loadJSON() functions in the reference.

JavaScript How to take all strings from an array and print them using filter?

If you don't understand the question, please see the code, i hope you will understand.
I want to take all strings that are in array, where in the same array have numbers for example and Booleans
I have an array in JavaScript
var names = ['a','v','c','Earth',2,3,4,12,3,3434,true,false,'Fire'];
How to check how many strings are in the array and print then using filter?
I am trying to learn how to use filter.
Just use typeof operator:
var names = ['a','v','c','Earth',2,3,4,12,3,3434,true,false,'Fire'];
var onlyStringValues = names.filter(function (value) {
return typeof value === 'string';
});
With filter in ES6 :
var names = ['a','v','c','Earth',2,3,4,12,3,3434,true,false,'Fire'];
var strings = names.filter(value => typeof value === 'string');
console.log(strings); // [ 'a', 'v', 'c', 'Earth', 'Fire' ]
Try this!
function stringFilter(arr) {
var filtered = [];
for(var i = 0; i < arr.length; i++){
if(typeof(arr[i]) === 'string') {
filtered.push(arr[i]);
}
}
return filtered;
}
You can use typeof condition to select all strings, these can then be added to a new array, of which you can get the length and also print them out if you like.
For more information go here:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/typeof

Javascript check every char in a string and return array element on corresponding position

Got a string that is a series of 0 or 1 bit and an array of values, if in the string are characters that are set to 1, I need to return the corresponding value from the array.
example: mystring = "0101"; myarray =["A","B","C","D"]; then result = "B,D"
how can I get this result?
for(var i=0;i<mystring.length;i++){
if(mystring[i] != 0)
{
result = myarray[i];
}
}
Your code seems to work just fine, so you can just add another array and push the values on to that:
var result = [];
for (var i = 0 ...
result.push(myarray[i]);
http://jsfiddle.net/ExplosionPIlls/syA2c/
A more clever way to do this would be to apply a filter to myarray that checks the corresponding mystring index.
myarray.filter(function (_, idx) {
return +mystring[idx];
})
http://jsfiddle.net/ExplosionPIlls/syA2c/1/
Iterate through the characters in the binary string, if you encounter a 1, add the value at the corresponding index in the array to a temporary array. Join the temporary array by commas to get the output string.
I am not really sure if this is what you are looking for, but this returns the array of matches.
var result = [];
for(var i=0;i<mystring.length;i++){
if(parseInt(mystring[i]) !== 0 ) {
result.push(myarray[i]);
}
}
return result;
result = new Array();
for(var i=0;i

jQuery substring

I have a key value pair something like this. this response comes back from the service in API.
var str = { "key1":"value1",..}
I need to use something lik this
for(var value in str) {
//I need to get only the value here. Eg: value1,value2 etc
}
how to get only value1 from this array using jquery sub string?
You can loop through an object (= key/value store) like this:
for (var key in items) {
var value = items[key];
// do things with key and value
}
If the response comes back as a set of (key, value) pairs, then you cannot really select the "first" value, because JSON objects do not have an order to their fields (different parsers may and probably will return the values in different order). You must know which key you want to access.
var str = { "key1":"value1",..}
for(var val in str) {
var strval = str[val];
}
var str = { "key1":"value1","key2":"value2","key2":"value2"};
var keyItems,valItems;
for(key in str){
keyItems.push(key);
valItems.push(str[key]);
}
// keyItems is array of all keys
// valItems is array of all values.

Categories