accessing JSON array item from another array - javascript

I'm a JS n00b, so my apologies for asking something so simple. (It's so simple that the rest of SO is providing more complex answers than I need.) I have a JSON array like this:
var comics = {"spider":"Spiderman", "bat":"Batman", "super":"Superman", "aqua":"Aquaman"};
And I want to access items in that array from another array, like so:
var childhood_heroes = {"fire":"Firefighters", "jordan":"Michael Jordan", "superhero":[comics.super, comics.bat]};
I'm attaching it with jQuery to a div in my HTML with:
$('#which_heroes').click(function() {
$('#jobs').html(childhood_heroes.fire);
$('#sports').html(childhood_heroes.jordan);
$('#supers').html(childhood_heroes.superhero);
});
The first two work when the third is absent. The presence of the third breaks everything. What am I doing wrong?

This
$('body').html(["one","two"]);
Produces
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
So, your issue is that you're passing an array of strings to the jQuery .html() function, which apparently doesn't handle it too well. Turn it into a string before you pass it, something like
$('#supers').html(childhood_heroes.superhero.join(', '));
should work.
The two valid arguments for .html() from http://api.jquery.com/html/ are
html( htmlString )
.html( htmlString )
.html( function(index, oldhtml) )

You're accessing an Array where you probably want a String, you can use join() to put all the entries in the superhero array into a string:
$('#supers').html(childhood_heroes.superhero.join(", "));

Make sure comics is initialized before childhood_heroes.
And not to nitpick, but neither of the things you defined are JavaScript or JSON arrays. They're only "arrays" in the very loose sense of "associative arrays".

The pair: "super":"Superman" will cause probs as super is reserved, so comics.super will raise an error in IE at least.
Rename it, or use comics["super"] notation.

Related

Convert JSON with objects and arrays to String

I have a JSON object which looks like this:
{
files: ['test.mp4'],
name: ['testFile'],
hints: ['%YES%_%MAYBE%_%NO%']
}
And I need to convert it to a String so the output looks like this:
[{files=test, name=testFile, hints= %YES%_%MAYBE%_%NO%}]
Is this possible to achieve in Node JS? Thanks
I tried the following:
var x = {
files: ['test.mp4'],
name: ['testFile'],
hints: ['%YES%_%MAYBE%_%NO%']
}
console.log(JSON.stringify(x));
But the output looks like this:
{"files":["test.mp4"],"name":["testFile"],"hints":["%YES%_%MAYBE%_%NO%"]}
Still with the square brackets. I may not 100% know the keys and values in the object above.
Try
JSON.stringify(obj)
then you get a string with quotes etc.
JavaScript has JSON.stringify() method which can convert an object into string:
var x = {
files: ['test.mp4'],
name: ['testFile'],
hints: ['%YES%_%MAYBE%_%NO%']
}
console.log(JSON.stringify(x));
// result: '{"files":["test.mp4"],"name":["testFile"],"hints":["%YES%_%MAYBE%_%NO%"]}'
This will result in a string which can be transformed back to JS object with JSON.parse() method. If you still want to remove all brackets and quotes, you can simply use JavaScript's replace() method (replacing characters [, ], and " with empty string), but this will replace those characters in all your values (if any) and will result in (sort of) non-reusable string.
TL;DR Don't do this unless you absolutely have to (ie. you're dealing with a messed up API written by someone else that must have the data in this format)
If you want exactly the format listed in your question, then you're going to have to write your own stringify function that recursively walks through the object you pass to it and applies whatever rules you want to use. You will have to consider all the possible permutations of your object and spell out those rules.
For example, you've converted arrays with single elements in the initial object into strings - what happens if there is more than one element in the array? Should it be delimited by a comma or some other character? Should we just throw away elements after the first?
And once you've written the stringify function, you'll also have to write the corresponding parse function to reverse it. And it should be mentioned that in your example, you're throwing away information (eg. the file extension on the .mp4 file) - how are you going to handle that?
A much, much better way to approach this would be to do what other people have suggested here: use JSON.stringify and rewrite your code to use standard JSON objects. Why? Because the format is well documented and well understood and because the functions to convert are well tested. You will save yourself a whole lot of time and pain if you don't try to reinvent the wheel here.

How can I remove dynamic data in string before a value in that string? / using Lodash's _.trimStart with dynamic data?

I'm working urls returned from a server that I have no control over where and sometimes the urls return with extra data at the front.
For instance
sometimes it returns this
https://example.com/image/5119b3905.jpg
and this I can use, but sometimes it will return something like this
https://d1yww.cloudfront.net/9MA=/670x670/example.com/image/5119b3905.jpg
where I'd like to use remove everything before the example.com and to do that I could use something like lodash's _.trimStart method something like
_.trimStart('https://d1yww.cloudfront.net/9MA=/670x670/example.com/image/5119b3905.jpg',
'd1yww.cloudfront.net/9MA=/670x670');
but the d1yww.cloudfront.net/9MA=/670x670' is never static for me to do this and I don't know how to grab the dynamic data to use _.trimStart and I don't see any other useful lodash's methods and I don't know of any vanilla javascript ones.
TLDR: How can I remove dynamic data in string before a value in that string (in this example everything before the example.com)
You don't need lodash to do that
var str = 'https://d1yww.cloudfront.net/9MA=/670x670/example.com/image/5119b3905.jpg'
str.substr(str.indexOf('example.com'))
You could search for a Regular Expression
For Example:
/\/([-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b)\//g
and look for the second match

jQuery/JavaScript regex return matched text from string

I am trying to create a fairly complex system for my website. I want to be able to write some pseudo like code and then parse it to make it do something in my back-end.
My data is inside two $.each loops as this is an Object of data with multiple levels to it.
For instance, I want to take a string like this:
"<!this!> == <!PropertyStreetNumber!>"
Then how I would like for the above code to executed is this:
FormData[parentKey][this] == FormData[parentKey]["PropertyStreetNumber"]
Thanks for any help!
Here's some of my code, the code where this would need to go in (see commented area)
http://jsbin.com/liquvetapibu/1/
Is there any restriction not to use regular expressions on JavaScript?
You could do something like this:
var myString = "<!this!> == <!PropertyStreetNumber!>";
var aux = /<!(.*?)!> == <!(.*?)!>/.exec(myString);
The value of aux will be an array with 3 elements:
The string that was tested.
The first element within <! !>
The second element within <! !>
Then it would depend on what the content on each one is: in your example this is an object, while you seem to use PropertyStreetNumber as a string (maybe a typo?). If you want to use it as an object, you will have to use eval() (e.g.: eval(aux[1])) while if you want to use it as a string, you can use it directly (e.g.: aux[2]).
Conceptually, the first thing you would need to do is determine the type of statement you are working with. In this case, a comparison statement. So you need a regex statement to filter this into a "statement type".
Once you do that, you can figure out what the arguments are. So you create a regex to pull out the arguments on each side of the operator.
Next, the strings that represent action code items need to be parsed. The this argument is actually an object, whereas "PropertyStreetNumber" is a string. You've got to be able to determine which is which. Then you can filter that into a function that has been created specifically to handle those statements types.
If at all possible, I would try to avoid the use of eval(). You can get into trouble with it.
you could try with
var beg = str.indexOf("== <!") + 5;
to find the index of the beggining and then slice counting the chars from beginning like
str.slice(beg, -2);
and from there build the rest.
couldnt that work?`

How to fetch comma separated values from mentioned string

I want to fetch comma separated IDs and types from below string.
I tried through split but that requires multiple split to fetch desired result.
Please suggest an efficient way to fetch desired output like like 1234,4321 using js/jquery.
var tempString=
'[{"id":"1234","desc":"description","status":"activated","type":"type","name":"NAME"},
{"id":"4321","desc":"description1","status":"inactivated","type":"type","name":"NAME1"}]';
To get "1234,4321", you can do
var ids = tempString.map(function(v){return v.id}).join(',');
If you want to be compatible with IE8, then you can do
var ids = $.map(tempString, function(v){return v.id}).join(',');
Following question edit :
If tempString isn't an array but really a JSON string, then you'd do
var ids = $.map(JSON.parse(tempString), function(v){return v.id}).join(',');
As pointed out, that's not a String in your example. Some quotation marks went missing.
At any rate, look into #dystroy's answer, but I think you are dealing with JSON objects, and you should probably be useing a json parser (or even javascripts raw eval if you must) and then fetch your components as object properties and arrays.
Check out jquery's parseJSON
You should use any Javascript parser api for JSON to decode the given string into keys and subsequent values. As mentioned by 'Miquel', jQuery has one
first off what you have above isn't a string, it is an array of objects.
BUT
if it were a string (like so )
var tempString = '[{"id":"1234","desc":"description","status":"activated","type":"type","name":"NAME"}]
[{"id":"4321","desc":"description1","status":"inactivated","type":"type","name":"NAME1"}]';
Then you would want to use something like .match();
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/match
var IDs = tempString.match(/([0-9]+)/gi);

How to get object values and properties in jquery?

I am using jQuery selector to get the values of all CMS components on the page using $('div.cmscomponent') but how can I test this to see if am actually getting the list of compoents on the page.
I use:
var temp = $('div.cmscomponent');
alert(temp);
and result that I get is [object OBJECT] and so how can I test this ? and how can I get values of the object and its properties.
$() returns a jQuery wrapper object, whose contents is usually a list of DOM elements, along with properties and methods that apply to those elements.
If you want to get an element, you can access them using array-style indexes or the get() method:
alert(temp[0].tagName); // Fetch the first element, alert the `tagName`
alert(temp.get(1).tagName); // Fetch second element, alert the tagName
To check to see how many elements the result contains, you can use .length, just like you would on an array or collection/nodelist:
alert(temp.length); // Alerts number of elements found.
Here is a javascrip include that will enable you to view object structure and information.
EX: dump(temp, true);
http://www.netgrow.com.au/files/javascript_dump.cfm
Well it depends on what you want to know about the matched objects. Some examples:
var temp = $('div.cmscomponent');
alert(temp.length); // number of matched elements
// Alert each id attribute of every matched element
$(temp).each(function(index) {
alert(index + ': ' + $(this).attr("id"));
});
var temp = $('div.cmscomponent').length;
alert(temp);
If by "how can I test this", you meant "how can I write a unit test for this?", the answer is that you shouldn't. You didn't write jQuery, so you should assume it's already been unit-tested. (If there were a problem with jQuery, though, you can write integration tests would catch this.)
On the other hand, if you meant "how can I sanity-check what jQuery is telling me to make sure I didn't goof on the inputs?", there are a few ways:
Check that .length matches the expected number of items.
Check that an XPath query for the same nodes ("//div[#class='cmscomponent']") returns the same number of values.
Check that the content of the Nth node matches what you expect.
Otherwise, it's probably best to use a third-party tool like Firebug.
If all you want to do is test if your code is doing what you expect, Firebug is your friend here. It will give you a console to type a command like $('div.cmscomponent') and then interactively explore the results that are returned by it.
You can then mouseover each item that your command returned and it will be highlighted on the page, so you can see which item the command returned, and if those items are the ones you expected/wanted.

Categories