Javascript Take JSON string convert to array [duplicate] - javascript

This question already has answers here:
How can I convert a comma-separated string to an array?
(19 answers)
Closed 3 years ago.
*****No JQUERY*****
I have a string passed into my Javascript that looks like below. I want to convert it into an array.
I have
{"test":"1,180,35"}
I want
an array where index 0 = 1, index 1 = 180, index 2 = 35.
How would I achieve this?

Parse the string, pull out the property value for property test, split it on ,.
var input = '{"test":"1,180,35"}'
var jsObj = JSON.parse(input);
var arr = jsObj.test.split(",");
console.log(arr);

use JSON.parse() to convert a string into a json object.
But, you are looking to parse a series of numbers into an array, so what you really want is split(",")

Use the JSON object
let arr = JSON.parse('{"test":"1,180,35"}').test.split(',');

For example:
var yourData = `{"test":"1,180,35"}`
JSON.parse(yourData).split(',')

Related

Is there a way to add each value to the first one in the for loop in JS? [duplicate]

This question already has answers here:
Easy way to turn JavaScript array into comma-separated list?
(22 answers)
Closed 2 years ago.
I have 4 different values, when looping through an array. Is it possible to add the values together like you would in Java's StringBuilder append?
I want something like this when doing a console.log():
28.0334307,-25.872523799999996, 28.031527552564445,-25.87632233243363
Now I am just getting it one for one like this when doing a console.log():
28.0334307
-25.872523799999996
28.031527552564445
-25.87632233243363
Here is my code:
var coordinates = [28.0334307, -25.872523799999996, 28.031527552564445, -25.87632233243363]
for(var item in coordinates)
{
console.log(item);
}
you can get a string in-line separated by a comma with join() method, try this:
var coordinates = [28.0334307, -25.872523799999996, 28.031527552564445, -25.87632233243363]
console.log(coordinates.join(', '));
Try this:
var coordinates = [28.0334307, -25.872523799999996, 28.031527552564445, -25.87632233243363]
console.log(coordinates.join(' '));
var coordinates = [28.0334307, -25.872523799999996, 28.031527552564445, -25.87632233243363]
console.log(coordinates.join(' '));
The browser consoles displays an array like that in to be more readable. It's not an actual structural representation of how an array is. What you want is basically a string created by joining the elements of the array.
Array.join method can be used for this:
coordinates.join("'")
Use JavaScript array join() method to display values separated by comma.
The join() method returns the array as a string.
The elements will be separated by a specified separator. The default separator is a comma (,).

convert array of hashes to array of values in javascript [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 2 years ago.
I am an array of hashes and I want to convert it to array of values something like this
array of hashes [{text: "James"},{text: "developer"}]
convert this to
array of values ["James", "Developer"]
Please help me achieve this in javascript.
Using Object.values, you can get the values of each object.
const input = [{text: "James"},{text: "developer"}];
const output = input.flatMap((item) => Object.values(item));
console.log(output);

Creating dictionary using python from javascript var data [duplicate]

This question already has answers here:
Convert [key1,val1,key2,val2] to a dict?
(12 answers)
Make dictionary from list with python [duplicate]
(5 answers)
Convert list into a dictionary [duplicate]
(4 answers)
Closed 4 years ago.
trying to figure out how to do this and have yet to find a good solution. I pulled this data out of an XML response. It was in a var tag. Now what I would like to do is create a dictionary out of it. The domain.com should be paired with the number right listed behind it.
This is the data:
[
'cb131.domain1.com', '147827',
'cb143.domain2.com', '147825',
'cb175.domain1.com', '147454',
'cb190.domain.com', '146210',
'cb201.domain.com', '146208',
'cb219.domain.com', '146042',
'cb225.domain.com', '146282',
'cb900.domain.com', '148461',
'cb901.domain.com', '148493',
'cb902.domain.com', '148495',
'cb903.domain.com', '148497',
'cb904.domain.com','148499',
'cb905.domain.com', '148501',
'cb906.domain.com', '148503',
'cb907.domain.com', '148505',
'cb908.domain.com', '148507',
'cb909.domain.com', '148509'
]
So for example cb131.domain1.com should be paired with 147827, cb143.domain2.com paired with 147825 and so on.
Drawing a blank on a good quick solution on how to do this. Hopefully someone can help.
Thanks!
Edited with answer I choose below:
I choose this answer and also to help anyone else I add a nice way to print out the results (data is the string I obtained):
import ast
i = iter(ast.literal_eval(data))
dic = dict(zip(i, i))
for key , value in dic.items():
print(key, " :: ", value)
This should do it. Assuming the list is saved to a variable l:
keys = l[::2]
vals = l[1::2]
dic = dict(zip(keys, vals))
You can create an iterator from the list after using ast.literal_eval to parse it from the input text, zip the iterator with itself, and pass the generated sequence of tuples to the dict constructor:
import ast
i = iter(ast.literal_eval(data))
dict(zip(i, i))
Assuming you have the above in a python array called data, you can do:
new_data = []
for i in range(0, len(data), 2):
new_data.append((data[i], data[i+1]))
Now new_data would be a list of tuples. You could certainly create a better data structure to hold these pairs if you want.
I do not yet know Python that I can write a snippet, but:
initialize an empty dictionary in Python
create a for loop counting index from 0 to length of your array in steps of two.
inside add a dictionary entry with key of value at index and value at index + 1
perhaps check for duplicates
Does this answer help you?
This is Python - quickly google'd:
dictionary = { }
for idx in range(0, len(data), 2)
dictionary[data[idx]] = data[idx + 1]

Transform values in JavaScript array to values in an array [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 5 years ago.
Let's say I have the following Object.
const result = [{date:'2016-11-21',name:'Bob',score:0.1034947}{date:'2016-10-21',name:'Bill',score:0.2081911},{date:'2016-10-21',name:'Mary',score:0.234947},{date:'2016-10-21',name:'Bob',score:0.1034947},{date:'2016-11-21',name:'Bill',score:0.2081911},{date:'2016-11-21',name:'Mary',score:0.234947},{date:'2016-12-21',name:'Bob',score:0.1034947},{date:'2016-12-21',name:'Bill',score:0.2081911},{date:'2016-12-21',name:'Mary',score:0.234947}];
What I want to take that object and turn those values and put them in separate arrays. So for example,
dateArray = ['2016-11-21','2016-10-21', ....]
I am really quite new to JavaScript. I am trying to do it with map but not sure if I am on the right track. So thanks in advance!
var dateArray = [];
for (var index in result) {
var item = result[index];
dateArray.push(item.date);
}
You can use Array.prototype.map to transform your array to a new one by projecting every original value with the defined function.
var dateArray = result.map(function(r) {
return r.date;
});
This code literally means "take array result and make a new array dateArray of the same length where every item is a value of date property of corresponding item of result".
You can also use arrow-function, but it is only compatible with ECMAScript 6.
var dateArray = result.map(r => r.date);

Convert string to javascript array in MVC [duplicate]

This question already has answers here:
How do I write unencoded Json to my View using Razor?
(3 answers)
Closed 7 years ago.
I have ViewBag.Result with string value "[['Garreth','VP'],['Johan','IT'],['Test','QA']]"
I want to convert it as javascript array
var dataset =
[
['Garreth','VP'],
['Johan','IT'],
['Test','QA']
]
Obviously var dataset = '#ViewBag.Result' doesn't work because javascript treat is as string but not array. Any idea how to do this?
Thanks
Just remove the single quotes:
var dataset = #ViewBag.Result

Categories