Javascript Convert 'List()' to list [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 received data from another API. But I don't know how to convert and use data.
data example
{
...
answer:'List(value1,value2,value3,value4)',
...
}
I want to iterate all answer nodes. please help.

Approach
You could capture the group between List(...) and split that by comma ,
Regex test: https://regex101.com/r/xFf39R/1
const answer = 'List(value1,value2,value3,value4)'
const res = /List\((.*)\)/.exec(answer)[1].split(',')
console.log(res)
Reference
RegExp.prototype.exec()
Return value
[...] The returned array has the matched text as the first item, and then one item for each parenthetical capture group of the matched text.

Reading your data example... It seems like the answer is carrying a String as the single quote is presented in your data example.
answer:'List(value1,value2,value3,value4)'
^ ^
And the List(value1,value2,value3,value4) actually looks like some python List in system print.
Well, but this does not help in your direct question.
Assuming your want to get all four values into an array in javascript, do the followings
let data_example = {
...
'answer':'List(value1,value2,value3,value4)',
...
}
let answer_string = data_example['answer'].slice(5,-1)
let your_list = answer_string.split(',')
console.log(your_list)
//["value1","value2","value3","value4"]
But be careful... I assume your List() always start with 'List(' and end with ')'
See more on slice and split

Related

JavaScript parse text containing name value pairs [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 2 years ago.
Improve this question
I have some text string which is like a JSON string, but not an exact one. It is like below
First Name: John
Last name : Doe
Address :London
It will be better if an object can be extracted from this string, so that I can iterate over its properties (First Name, Address etc.) with for...in loop.
Any idea about how this can be done? Thanks in advance!
Simply make use of String.prototype.split() (once, to extract each line into separate item, then once again, to separate property names from values):
const str = `First Name: John
Last name : Doe
Address :London`,
result = str
.split("\n")
.reduce((acc, substr) => {
const [prop, value] = substr.split(/\s*:\s*/)
acc[prop] = value
return acc
}, {})
console.log(result)
.as-console-wrapper{min-height:100%;}

Convert array values into strings in javascript [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 3 years ago.
Improve this question
I have this array [ABC, QWE, XYZ]
I would like to turn it into ['ABC', 'QWE', 'XYZ']
When I try to manipulate values in the current array I get: ReferenceError: ABC is not defined
Any ideas on how should I do it?
Thanks!
Convert arrays element types:
Number to strings
var strArr = [1,2,3,4,5].map(String);
// Result: ["1","2","3","4","5"]
We can't do that directly but after little bit change you can do that...
So the current array you said like array [ABC, QWE, XYZ],
Lets design you keys in object first:
var obj = {
ABC:1, QWE:'somevalue', XYZ:new Date()
}
So I created object obj having your variables lets say the three variables, now lets convert:
var arr = [];
for (var key in obj){
console.log(key, obj[key]);
arr.push(String(key));
}
console.log(arr);// you will see the desire result.
Running example here : example

Proper array structure [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 6 years ago.
Improve this question
Commonly, arrays are formed like var array = ["some","string","elements"] or var array = [1, 2, 3]. Been searching for times, but I haven't seen articles that may clear my mind. Now, is it possible to have an array structure like var array = [some, string, elements]. As what can be observed, it was somehow a string without "".
To visualize my concern, I have this code
var data = []
for (var x = 0; x < arrayData.length; x++){ //arrData contains [1,2] structure
data.push("$scope.item["arrayData[x]"]");
}
//which gives var data = ["$scope.item[1], $scope.item[2]"]
I needed that var data to form like var data = [$scope.item[1],$scope.item[2]]. Is it possible?
EDIT
My bad, I haven't explained my query fully. The "$scope.item[" is a string, that's why I encapsulated it to ""
EDIT II
Is it possible to have an array structure like var array = [some, string, here]. Consider that some,string and here are not variables.
Don't complecate it, Just go with using JSON.stringify();
Your code should be
data.push(JSON.stringify("$scope.item[" + arrayData[x] + "]"));
You cannot have an array structure like var array = [some, string, elements]. There should be variables named some, string and elements.
$scope is a special variable in AngularJS. So, you should use it without "s. For example:
data.push($scope.item[arrayData[x]]);

JSON.parse doesn't produce proper arrays of object [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 try to pass my string below
{"1":{"11":{"cityid":1,"bpid":11,"name":"Golden Mile
Tower","time":"+00:00","sbpid":50043}},"2":{"34":{"cityid":2,"bpid":34,"name":"KL
Sentral","time":"+00:00","sbpid":50040}},"8":{"244":{"cityid":8,"bpid":244,"name":"Taman
Sri Puteri","time":"+00:00","sbpid":50042}}}
console.log(JSON.parse(str))
It doesn't become what I expect like below
Any idea why??
It woun't produce correct array, because you don't have it.
You have Object not Array
This is array, cause it starts from index 1:
{
"1":{"11":{"cityid":1,"bpid":11,"name":"Golden Mile Tower","time":"+00:00","sbpid":50043}},
"2":{"34":{"cityid":2,"bpid":34,"name":"KL Sentral","time":"+00:00","sbpid":50040}},
"8":{"244":{"cityid":8,"bpid":244,"name":"Taman Sri Puteri","time":"+00:00","sbpid":50042}}
}
and this is array :
[
{"11":{"cityid":1,"bpid":11,"name":"Golden Mile Tower","time":"+00:00","sbpid":50043}},
{"34":{"cityid":2,"bpid":34,"name":"KL Sentral","time":"+00:00","sbpid":50040}},
{"244":{"cityid":8,"bpid":244,"name":"Taman Sri Puteri","time":"+00:00","sbpid":50042}}
]
For converting Object to Array use loop, like :
var arr = [];
for( var a in your_object ){
arr.push(a);
}
JSON.parse will parse the string only so you are providing the object so it will not parse the object . so wrap your object with single quotes .
I have added the single quote in start and last . now you can check . it will return array .
JSON.parse('{"1":{"11":{"cityid":1,"bpid":11,"name":"Golden Mile Tower","time":"+00:00","sbpid":50043}},"2":{"34":{"cityid":2,"bpid":34,"name":"KL Sentral","time":"+00:00","sbpid":50040}},"8":{"244":{"cityid":8,"bpid":244,"name":"Taman Sri Puteri","time":"+00:00","sbpid":50042}}}');

Deduplicate across strings maintaining identity label [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 8 years ago.
Improve this question
JavaScript problem. Can this be done?
I have an input array containing anything between 2 - 5 strings, each with a semi-colon delimited label to identify it. I need to de-duplicate such that the output removes the duplicates but also maintains the string identifiers, grouping if necessary.
Input Array (3 elements)
string1;apple|string2;orange|string3;orange
Output Array (now 2 elements since 'orange' appeared twice)
string1;apple|string2/string3;orange
I don't mind helping people that are just starting with a new programming language or programming: (also a js fiddle)
var arr=["string1;apple","string2;orange","string3;orange"];
var finalArr= [];
var output = {};
for(var i in arr){
var keyVal = arr[i].split(";");
if(output[keyVal[1]]==undefined){
output[keyVal[1]] = [keyVal[0]]
} else {
//should be an array
output[keyVal[1]].push(keyVal[0]);
}
}
for( var i in output){
finalArr.push(output[i].join("/")+";"+i);
}
console.log(finalArr);
I think your best option for this would be to find a way to logically group this information.
Convert the pipe-delimited string into an array.
Iterate through the array
Assign each id/value pair to a property=value pair in a struct.
Strip out the id and delimiter so you're left with the string itself in the array.
Sort the array.
Deduplicate the array.
Iterate through the array.
Iterate through the struct to generate a list of properties which values match the entry.
Unset the properties which values match the entry to reduce time in future iterations.
This is only one way of doing it. I've given you some hints on how you can approach the problem, but it's up to you to code this.

Categories