I'm passing myself a string of results from php by ajax that I would like to put into a two dimensional array in JavaScript
The string looks like: value1^*value2^*value3^*value4***value1^*value2^*value3^*value4
I would like to split the values by '^*' into the first row of the dimensional array, then the next row would be after the '***'
Desired array:
var Text = [['value1', 'value2','value3','value4'],[value1','value2','value3','value4']];
You can use split() to split your string into an array of strings ( value1^*value2^*value3^*value4 and value1^*value2^*value3^*value4 ), after that you will need map() to creates a new arrays inside each array which we get before.
Example:
var str = "value1^*value2^*value3^*value4***value1^*value2^*value3^*value4"
str = str.split('***')
str = str.map((value) => value.split('^*'))
console.log(str)
You can do something like that
var input = "value1^*value2^*value3^*value4***value5^*value6^*value7^*value8";
var res = input.split('***').map(function(rowValues){
return rowValues.split('^*');
})
console.log(res);
Related
I want to convert a JSON string into a set of array containing the values from the JSON. after json.stringify(jsonmybe) and alert it display [{"role":"noi_user"},{"role":"bert_user"}] (which i saw as a JSON). I want to get the noi_user and bert_user and set them into a javascript array. something like ['noi_user','bert_user'] with quotes in each value.
I did the var stringy = json.parse() and the alert showing [object Object]. and further add this lines
for (var i = 0; i < stringy.length; i++) {
arr.push(stringy[i]['role']);}
and the arr I get was a value with comma when in alert but the comma missing as i display them in the text field and it becomes a long string like noi_userbert_user
What I really want is from [{"role":"noi_user"},{"role":"bert_user"}] to ['noi_user','bert_user']
Use JSON.parse and then reduce to get what you want,
var s = `[{"role":"noi_user"},{"role":"bert_user"}]`
var arr = []
try {
arr = JSON.parse(s).reduce((acc, val)=>[...acc, val.role], [])
} catch (e){
console.log("Invalid json")
}
console.log(arr)
Is this what you are loking for ? You can map on your array and just extract the role attribute of each datum.
const jsonString = ...
const data = JSON.parse(jsonString).map(data => data.role);
console.log(JSON.stringify(data, null, 2));
JSON uses double quotes to delimit strings and field names.
So you have a JSON string like
'[{"role":"noi_user"},{"role":"bert_user"}]'
You want to convert it to an object, then extract values of "role" fields of each element, put them all into an array.
Your example json string contains an array of user objects within "role" fields. Following code takes this list, loops through each user object and puts role's of each object into a separate array roleList.
var jsonStr = '[{"role":"noi_user"},{"role":"bert_user"}]';
var userObjList = JSON.parse(jsonStr);
var roleList = [];
userObjList.forEach(userObj => {
roleList.push(userObj.role);
});
console.log(roleList);
You could make a custom function to produce a sort of array_values in PHP but an indented and 2D level like so:
function array_values_indented (input) {
var tmpArr = []
for (key in input) {
tmpArr.push(input[key]['role']);
}
return tmpArr
}
var object = JSON.parse('[{"role":"noi_user"},{"role":"bert_user"}]');
var result = array_values_indented(object);
console.log(result);
I am getting a set of arrays in string format which looks like
[49,16,135],[51,16,140],[50,18,150]
Now I need to save them in an array of arrays. I tried it like
let array = [];
let str = '[49,16,135],[51,16,140],[50,18,150]';
array = str.split('[]');
console.log(array);
but it is creating only one array including all string as an element while I need to have
array = [[49,16,135],[51,16,140],[50,18,150]]
Add array delimiters to each end of the string, then use JSON.parse:
const str = '[49,16,135],[51,16,140],[50,18,150]';
const json = '[' + str + ']';
const array = JSON.parse(json);
console.log(array);
You are splitting it incorrectly, in the example, it will only split of there is a [] in the string
You can create a valid JSON syntax and parse it instead like so,
let str = '[49,16,135],[51,16,140],[50,18,150]';
let array = JSON.parse(`[${str}]`);
console.log(array);
Another way you could achieve this is by using a Function constructor. This method allows you to "loosely" pass your array.
const strArr = "[49,16,135],[51,16,140],[50,18,150]",
arr = Function(`return [${strArr}]`)();
console.log(arr);
I have an array that is combining the sources of multiple arrays using concat.
var tags = [].concat.apply([], [typeArr,genderArr,conditionArr]);
The items in the array are then filtered for any
tags = tags.filter(function(entry) { return entry.trim() != ''; });
However, I realized that, because of where the data comes from, some items are coming in as strings with commas, such that tags array looks like the following: ["red","blue","green,yellow,orange","purple,black"]
How could I split the items so that the tags array looks like ["red","blue","green","yellow","orange","purple","black"]? I was thinking something where I loop over the array and then use split to reinsert these into a new array?
I'm trying to do it with vanilla JavaScript
Use Array.join() by comma (or .toString() which does the same) to convert the array to a single string, the use Array.split() by comma to get an array of individual items:
var arr = ["red","blue","green,yellow,orange","purple,black"];
var result = arr.join(',').split(',');
console.log(result);
You could use a Set for getting unique values after the values have been separated.
var array = ["red", "blue", "green,yellow,orange", "purple,black", "green,red"],
result = Array.from(new Set(array.join(',').split(',')));
console.log(result);
var data = ["red","blue","green,yellow,orange","purple,black"];
data = data.reduce(function(prev, next) {
return prev.concat(next.split(','));
}, []);
console.log(data);
I have an array that contains multiple strings. I need to store each string minus the first letter and then concatenate them into a sentence.
I am trying:
var missingFirstLetter = array[i].splice(1);
What I have found online guides me to believe this should work, but it doesn't work as intended.
You should slice (not splice!) each element of the array and then store it back into an array, which you can do with Array#map, which maps each element to a new value, in this case the string without the first letter:
var arrayNoFirstLetter = array.map(el => el.slice(1));
This will iterate through the array and map each element to a new string without the first letter and store the new array of strings into arrayNoFirstLetter. Make sure to use String#slice to get a section of a string, because there is not String#splice method. (maybe you mistook it for Array#splice?) Then you can use Array#join to join them with a delimiter (which is the string between each element when joined together):
var joined = arrayNoFirstLetter.join(""); //join with empty space for example
For example:
var array = ["Apples", "Oranges", "Pears"];
var arrayNoFirstLetter = array.map(el => el.slice(1)); // ["pples", "ranges", "ears"]
var joined = arrayNoFirstLetter.join(""); // "pplesrangesears"
Try this:
var a=["hHello","+-I-am","d-evil"];
var x;
var z="";
for(var i=0;i<a.length;i++){
x=a[i].substring(1);
z=z+x;
}
console.log(z);
Result is :
Hello-I-am-evil
Is it what you wanted?
var strings = ['string1', 'string2', 'string3'],
stringsNoFirstCh = [];
for(key in strings){ // Iterates through each string in an array
let string = strings[key];
var s = string.substring(1); // Gets a string starting from index 1, so omits the first char
stringsNoFirstCh.push(s); // Add to a new array: ['tring1', 'tring2', 'tring3']
}
var string = stringsNoFirstCh.join(''); // Transform to a string: tring1tring2tring3
I want to extract all JSON objects from a string randomly containing them and add them to an array.
Sample string:
"I was with {"name":"John"}{"name":"Anne"}{"name":"Daniel"} yesterday"`
how can i extract the JSON objects from this sample string?
One approach to this is to use the str.search(regexp) function to find all parts of it that fulfill the JSON regex found here. So you could write a function that searches over the string for regexp matches.
To actually extract the object from the string you could use these two functions for the regex and then loop over the string until all objects have been found.
var match = str.match(regex);
var firstIndex = str.indexOf(match[0]);
var lastIndex = str.lastIndexOf(match[match.length-1]);
var JSONobjects = [];
while( str.match(regex){
//extract the wanted part.
jsonObject = substr(str.indexOf(match[0],str.lastIndexOf(match[match.length1-]));
//remove the already found json part from the string and continue
str.splice(str.indexOf(match[0],str.indexOf(match[0] + jsonObject.length());
//parse the JSON object and add it to an array.
JSONobjects.push(JSON.parse(jsonObject));
}
var a = JSON.parse('{"name":"John"}');
a ==> Object {name: "John"}
var b = [];
b.push(a);