Javascript: how to access each element in an array - javascript

I query two arrays from the database and turn them into json format. The set up is like this:
{"groups":"[apple,bee,car,dogs,egos,fruits]", "members":"[g,h,i,j,k,l]"}
I am trying to access each element in groups. The groups array is a list. I tried using index, and it's returning me groups[0] = 'a', groups[1] = 'p'... So using index doesn't work.
I also want to count how many elements in the groups array or in the members array, and using .length only give me back the character length, not the actual numbers of elements.
Any advice would be appreciated. Thanks.

JSON.parse(groups) will not work, because [apple,bee,car,dogs,egos,fruits] is not correct JSON string.
["apple","bee","car","dogs","egos","fruits"] - is correct JSON string, that can be parsed.
P.S. members is not correct JSON string too.
// If you have some data
data = {
groups: ["apple", "bee", "car", "dogs", "egos", "fruits"],
members: ["g", "h", "i", "j", "k", "l"]
};
// you can convert it to JSON string
jsonData = JSON.stringify(data);
console.log('JSON data: ', jsonData);
// and then parse this string
restoredData = JSON.parse(jsonData);
// after this you can access object members again
console.log('groups[0]: ', restoredData.groups[0]);

This is happening because "[apple,bee,car,dogs,egos,fruits]" it's an string. You have to parse it before accessing the element.
Let's say that you have the JSON in the variable test, then we have to delete [ and ] and split the string like this:
test.groups = test.groups.replace("[", "")
test.groups = test.groups.replace("]", "")
test.groups = test.groups.split(',')
And then now it contains:
["apple", "bee", "car", "dogs", "egos", "fruits"]

You should consider constructing the array differently from the database.
You are getting those letters because they are in the position in the string that you are referencing with the index.
Consider using regex and the split() function to parse them as they are now:
var obj = {"groups":"[apple,bee,car,dogs,egos,fruits]", "members":"[g,h,i,j,k,l]"};
// Regex replaces the square brackets with blank spaces and splits by the
// comma into an array
var groups = obj.replace(/[\[\]']+/g,'').split(',');
var members = obj.replace(/[\[\]']+/g,'').split(',');
Now groups[1] will return 'bee'.
Read more about split() here.

It doesn't work because all elements of the array are in one string.
As has been mentioned this not correct JSON formatting, but sometimes you don't have control over how you get information. So although this is not a recommended answer, you could use simple string parsing to get back the values you want by doing, something like:
var stuff = JSON.parse('{"groups":"[apple,bee,car,dogs,egos,fruits]", "members":"[g,h,i,j,k,l]"}');
var groups = stuff.groups.split("[")[1].split("]")[0].split(",");
var members = stuff.members.split("[")[1].split("]")[0].split(",");
console.log(groups); // ["apple", "bee", "car", "dogs", "egos", "fruits"]
console.log(groups[1]); //bee
console.log(members[0]); //g
I would like to reiterate this is not an ideal solution, but sometimes it is all you can do.

Related

Find which letters from the input match somewhere in array

I have an array of strings. A user typed “ztaf”. How can I use JavaScript to find which of the letters the user typed match somewhere in the array? The answer should be “taf”.
var array = [ "tofu", "fish", "meat" ];
var user_type = "ztaf";
var found = ""; // It should be "taf".
I have tried it, but it keeps saying there is no match.
You can achieve this by using String.split() along with the Array.filter(), Array.join() and String.includes() methods.
Live Demo :
var array = ["tofu","fish","meat"];
var user_type = "ztaf";
var found = user_type.split('').filter(char => array.join().includes(char));
console.log(found.join(''));

JSON split value at first space

I'm very new to JSON and I have not found the answer searching. I'm thinking my question is just too simple
I have a simple JSON
{
"Application": "The Best Application",
}
My goal is to split the value at the first space and store the next word in a variable, which in this case would be the word Best
I've tried the following, but it is not working:
var json = '{"Application":"The Best Application",}';
var obj = JSON.parse(json);
var obj2 = obj.result.split(" ");
console.log(obj2.result);
.split() returns an array and you want to take an item under index 1. Also note that JSON.parse() returns an object and you want to read the value from Application key:
var json = '{"Application":"The Best Application"}';
var obj = JSON.parse(json);
var obj2 = obj["Application"].split(" ");
console.log(obj2[1]);

A nested array of string to number

I'm looking to convert a nested array of the type string to type float, or alternatively parsing it from a text file. Format is something along the lines of this [45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]
The first step would be to create valid JSON from your string.
If your input will always follow the schema you showed us, you could just prepend and append brackets to the string. This is not a pretty solution though. You should first check if you can get valid JSON in the first place.
A solution could look like this, provided that the input string will always follow the format of "[float, float], [float, float]":
const input = "[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]";
// Add brackets in order to have valid JSON.
const arrayString = "[" + input + "]";
// Parse the string into an object.
const parsedArray = JSON.parse(arrayString);
// Flatten the nested array to get a one dimensional array of all values.
var flattenedArrays = [].concat.apply([], parsedArray);
// Do something with your values.
flattenedArrays.forEach(floatValue => console.log(floatValue));
You can use JSON.parse, if your numbers are actually numbers in a JSON (serialized without quotes).
let test = "[[3, 4.2], [5, 6]]";
let test2 = JSON.parse(test);
console.log(test2);
Otherwise you can simply convert your array of array of strings to array of array of numbers using + and some array mapping. :
let test = [["3", "4.2"], ["5", "6"]];
let test2 = test.map((x) => x.map((y) => +y));
console.log(test2);
Of course, you can combine both solutions if for some reason you don't control the input and have a JSON containing strings.
This thread shows you how to loop through an array of strings to convert it to an array of floats.
i hope this will work..
var input = [[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]]
var output = [];
input.forEach(o => {
o.forEach(s => parseFloat(s))
output.push(o);
})
console.log(output);

How to retrieve data from array where inside the array you have xml data?

Imagine I have array as below
myArray holds two values as
0: <maintenanceshortterm type="System.Int32">1111</maintenanceshortterm>
1: <maintenanceshortterm type="System.Int32">1234</maintenanceshortterm>
I want to retrieve the values 1111 and 1234 using jQuery/JS only.
Please please help me how I can retrieve values like that? You can probably guess that that values inside the array are actually coming through xml.
Assuming each item is only a maintenanceshortterm and there's no nested structure or anything, a simple regex would do it:
const arr = [
'<maintenanceshortterm type="System.Int32">1111</maintenanceshortterm>',
'<maintenanceshortterm type="System.Int32">1234</maintenanceshortterm>'
];
console.log(
arr.map((str) => str.match(/>([^<]+)</)[1])
);
also you could make use of the string split mehtod
var arr = new Array('<some xml ...>1111</>', '< some xml...>1234</>');
//split the first string by '>'
var firstItem = arr[0].split(">");
//firstItem now contains "<some xml ...", "1111", ""
//want item at index 1
document.writeln(firstItem[1]);
//likewise for the second value

Javascript: Remove last occurence of comma in span tag

I want to append object keys to span tag with class result and separate them with comma. But I can't remove last occurence of comma in text.
Result: <span class="result"></span>
Javascript:
for (key in obj) {
$(".result").append(key + ",");
}
So, for example, instead of 1,2,3, it must be 1,2,3
You may use the "join" method in order to combine array elements with separators between them like so:
var sample = ["1", "2", "3"];
console.log(sample.join(","));
//outputs: 1,2,3
It does not work on object properties though, so you have to use Object.keys() in order to convert your object into an array of its properties (supported in most browsers).
$(".result").append(Object.keys(obj).join(","));
Try solution in fiddle join() function of array comes in real handy
// if array
var ele = ["1", "2", "3"]
$(".result").append(ele.join(","));
// if object
var ele1 = { "a": 1, "b" :2, "c" : 3}
var value = $.map(ele1, function(k, v) { return k;}).join(",")
$(".result1").append(value)
It will replace all trailing ','.
var str = "1,2,3,"
str.replace(/,+$/g,"")
DEMO
You can also use the array methods:
var test = "a,b,c,,,";
var test1 = test.split(",");
while (!test1[test1.length-1]) {
test1.pop();
}
console.log(test1);
test = test1.join(",");
console.log(test);
Do it like this
var str = "1,2,3,"
str = str.slice(0,-1)
console.log(str) //"1,2,3"
For your SPAN I did this.
$('.result').text($('.result').text().slice(0,-1))
I would do, instead:
var results = (Object.keys(obj)).join(",");
$(".result").append(results);
Far more simpler. More efficient ;)
If you do an append in a loop, the page will be redrawn every time you add a key. That's slow.
Plus, with Object.keys(obj) (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) you get an array with all the keys of the object, and you only need to join all elements in a string, separating it with a comma. So more concise, no?

Categories

Resources