JavaScript parse text containing name value pairs [closed] - javascript

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%;}

Related

Javascript Convert 'List()' to list [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 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

JavaScript Array Search and Remove [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 a scenario where I have an INPUT, The User enters some text, like for ex: Cat.
I need to search an Array and check if the input from the User is present in my Array.
If it is present I ould want to remove that item from the Array and return a new Array with that item removed.
Suppose I have an arraylist like,
let arrayList = ["cat","mouse","dog"];
User INPUT = cat;
I want to check if the cat is present in arrayList , If yes then I want to remove the cat from the arrayList and want to have a new array that does not contain cat in it. Hence any INPUT provided by User needs to be removed from an array and return me a new array without that item.
You can use filter function to filter the array. Reference link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
function filterArray(arr, searchString) {
var result = arr.filter(function(e) {
return e != searchString;
});
return result;
}
filterArray(arrayList, "cat") // This will return ["mouse", "dog"];

How to loop over a nested JavaScript object in jQuery? [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
I am new to Javascript and jQuery. I am trying to create something like this (object) below and read the keys and retrieve the values.
var members = {unit:1,name: ["AA", "AB"],userid:["0001","0002"],
{unit:2,name: ["BA", "BB"],userid:["0011","0012"]};
if 'Unit' == 1 then display name array.
Basically I want loop through the object and retrieve the value.
I think you member should be like this
var members = [{unit:1,name: ["AA", "AB"],userid:["0001","0002"]},
{unit:2,name: ["BA", "BB"],userid:["0011","0012"]}];
var members = [{unit:1,name: ["AA", "AB"],userid:["0001","0002"]},
{unit:2,name: ["BA", "BB"],userid:["0011","0012"]}];
members.forEach(function(v,i){
if(v.unit==1)
{
console.log(v.name);
}
});
I guess this is want you wanted, an object within an object. Where 'unit' is the key for retrieving the objects within the object.
var members = {
1: {
name: ["test","test"],
userid: ["0001","0002"]},
2: {
name: ["test2", "test2"],
userid: ["0011", "0012"]}
};
console.log(members[1]);

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

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