Taking the first JSON string that contains a specific phrase (Javascript) - javascript

I am trying to get the value of the first string in JSON containing the string amogus. I have no idea how to start.
I want it to get the first JSON string that has amogus in it, then take the entire string, including the number included in the found string.
JSON file:
{stuff: ["hosds29083", "amogus1208", "amogus1213"]
As you can see, the JSON file contains multiple strings, and some of them contain amogus. My desired output is amogus1208, which is the first string containing amogus.
Does anybody know how this could be done? Thanks.

You can use Array.find() to find the first matching item and use String.includes() to check the items in the callback function in find(), as follows:
const data = ["hosds29083", "amogus1208", "amogus1213"];
const firstOne = data.find(str => str.includes('amogus'));
console.log(firstOne)

Get the JSON content into an array then use .find() on it.

Related

How can I work with in JavaScript a single HTML input field as an array?

After hours of searching and testing I finally have decided to post a question.
I need to be able to make something like this to work with a function.
var myCSV = [1,3,5,6];
Currently, I can grab the CSV from the database as that is how it is stored, myColumn = 1,3,5,6. I can get it to pass as an AJAX success response but it seems to want to add quotes. I then tried to add JSON encode to my PHP side of things and JSON Parse to the success call but still cannot get the function to work. The end goal is to select checkboxes based off the csv value.
This works
var FilterArray = [1,3,5,6]; // Manually added these numbers as is for testing
$('#myForm').find('.checks').each(function () {
$(this).prop("checked", ($.inArray(parseInt($(this).val()), FilterArray ) != -1));
});
After trying to much to get my AJAX success response to work in the FilterArray, I decided to just pass it to an input value and work with it. However, cannot figure out how to not treat it as a string when I pass it to the function. Here is what I have tried.
In my getCSV.php I have at the end this
json_encode($foundCSV);
In my AJAX Success
var FilterArray = JSON.parse(response);
I have also tried it without the json_encode and just sending it to an input value which does not add quotes.
So in summary, how can I take a csv e.g. 1,3,5,6 stored value and pass it to a function that works as shown above?
Assuming you have your string in a variable, called response, and its value is "1,3,5,6", you can translate it into an array of integers with this:
response.split(',').map(e => parseInt(e))
and you can then pass the result of this to your function.
Sticking to your naming, the code should look like this:
var FilterArray = response.split(',').map(e => parseInt(e));
What the code does:
takes the response and split it by using the comma character as a delimiter
this will create an array of strings
for each string in that array, tries to parse it as an integer (an ID, i guess?)
Clarifying question: What does your $foundCSV look like on the PHP side, before you json-encode it? Is it an array or a string with comma-separated numbers? You might want to check with your developer tools/debugger what the Ajax response contains. It sounds like you have a string but expect an array.
If that's the case, you can create an array on the JS- or PHP-side. For the JS-side, consult #GregorioPalama's answer.
Alternatively, you could do this on the PHP-side, which might be shorter:
$response = explode(',', $foundCSV);
and then work with json_encode($response).

How to parse the following json string into an object?

var jsonString = '{"DeviceId":3,"results":{"1":"[{\"x\":513,\"y\":565,\"width\":175,\"hight\":208}]"}}';
var message = JSON.parse(jsonString);
I got an error saying Unexpected token u in JSON at position 0
at JSON.parse.
Could you please guide me what's wrong?
THanks in advance!
At the last few characters looks wrong. The :212 has no sense as the value (that long array) for key "1" was already set, so that later :212 looks weird
Also enclosing it in single quotes it makes that all be like a huge string, and not as an array structure.
See Results key as value contains a sub array which contain "1" key which as value contains a string enclosing another json array (but escaped as plain string, so no structurally accesible for the main object . But that string if post -processed the :212 is paired to what? , no key, no comma neighter , to the precedent whole array which already was the value, not the key?. Anyway weird.
In your JSON string, there is wrong something with ":212", as it's not valid JSON, because it doesn't have any property that it's mapping the value for. For example, you are mapping values for width and height with properties keys. But for "212", there is no property.
Here is the above JSON formatted:
var jsonString = '{"DeviceId":"3","results":{"1":"[{\\"x\\":513,\\"y\\":565,\\"width\\":175,\\"hight\\":208}]"}}'
var message = JSON.parse(jsonString);
If you want to format the results, you can do to it, there is no error on it:
JSON.parse(message.results['1'])
Here is the JS Bin link for above code: https://jsbin.com/fiyeyet/edit?js,console
Just an advice
Professional code is all about proper spacing, proper identation , proper commenting, don't try to write down all within one single line, structure it VISUALLY nice to see nice to read nice to comprehend, and you will be approved in most jobs.
Hint: declare a normal array/object , convert it to json string using the proper function, then use the string variable returned by the function to test your code or whatever doing. That way, you can write down in the source really nice the structure.

MongoDB array turned into string on database

I have problem with Mongo/express array parsing. A array from body seems to be correct when I console.log response in node console. But the problem is when I try to save the body to mongo.db using insert.one method, the post is saved but the array turns into string, which is bad for me.
This is what I'm sending to mongo (the data is ok, i console.log it, array is not string here)
{
createdBy: this.userName,
postContent: this.post,
tags: this.tags,
addedAt: new Date()
};
And this is what is stored in database
Update:
When I hardcode array into payload it's showed correctly as an array in mongo.
But of course problem still exist for dynamic data
You should be able to use JSON parse along with a replace to force it to accept the string as an array, like this:
const array = JSON.parse(this.tags.replace(/'/g, '"'));
Then set tags to the value of array:
tags: array
Use data type as array -- 4 and use .pretty().
Generally if you use find() method returns data in a dense format.
By using cursor.pretty() you can set the cursor to return data in a format that is easier for humans to parse

NaN When trying to print json values

I was trying to parse a json which I got as a response of querying connections in linked in.
when I do JSON.stringify in an array as a whole I can see values in console.log
but when I try to take individual values inside array I get NaN.
Why can I not get Individual values when I can see the array as a whole.
here is the code
var response = jQuery.parseJSON(data);
var person = response.person[0];
in the above code I am getting data as a response of an ajax call
person is an array inside, I can stringify the array as a whole.
if I do
console.log(JSON.stringify(person));
I will get
{"id":"someId","first-name":"someName","last-name":"someName, DMC-E, DMC-D","picture-url":"https://soempicture"}
but When I try to take it individually
console.log(person.first-name);
I get NaN , and trying to strigify it results in Null
am I missing something, should I do string split to get the values?
Thank you
You can't access the first-name property using period notation, as the name contains a dash.
The code will be interpreted as person.first - name, i.e. the person.first property minus the name variable.
Use the bracket notation for any property where the name can't be an identifier:
console.log(person['first-name']);
To access a key that contains characters that cannot appear in an identifier (-), use brackets, i.e.:
person["first-name"]

Get first item from comma delimited object

Hi I have an object rowObject passed into a javascript function. When I inspect it by putting it into an alert I see something like:
435,345,345345,56456
What I want to achieve is to get the first integer ie. 435 from the list.
I know how to do this in server side code but client side code.
Can someone please help me with this?
Assuming that your rowObject is a string, you can use .split() to split the comma delimited list. At this point you can access the array of items by index and get the first element.
http://www.w3schools.com/jsref/jsref_split.asp
An Example
var rowObject = "435,345,345345,56456";
var splitRowObject = rowObject.split(',');
if(splitRowObject.length > 0)
alert(splitRowObject[0]);
alert() is calling objects toString() method, so you don't know the structure of the object. It is a good idea to use console.log instead for logging objects as in modern browsers it will allow you to explore structure of the object in the console window.
One of the solutions you can do without knowing the structure is:
var firstInteger = +rowObject.toString().split(',')[0] // 435
That works if rowObject is string, array or everything else :).
EDIT: Putting + before the string will try to convert it to a number.
Have you tried rowObject[0]?
The fact that the alert shows 435,345,345345,56456 doesn't mean that the object is string, it could be Object and Array as well as their toString method implemented to display it in such way. For example the native array is also looks like that when alerting or converting to string, so you need to call toString method at first then split it by comma:
var firstInt = rowObject.toString().split(',')[0];

Categories

Resources