How to fetch comma separated values from mentioned string - javascript

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);

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

JSON.parse & JSON.stringify handling long integers as strings

I have the problem, that I need to parse long integers in my API. Since I don't do anything arithmetically, it is the easiest to handle them as Strings. I tried Bignumber.js, but it starts complaining if numbers are longer than 15 characters. Unfortunately I have to handle them as well.
Since I don't do anything arithmetically with it and actually even store those numbers as String I would like a JSON Parser that parses too big numbers as Strings and is capable of also treat them as numbers in JSON.stringify.
I tried the stringify with a replacer function, but I could not get rid of the quotes around my number.
I also did not find a library, that just takes care of this issue.
Edit / Clarification
I want my big number to be a String in javascript, but a number in JSON (after JSON.stringify)
e.g. Object in Javascript
var myObj = {
id: "89074987798719283473" // <-- String within javascript
}
var objString = JSON.stringify(myObj)
Now my objString should be
{id: 89074987798719283473}
And NOT
{id: "89074987798719283473"}
If you absolutely must do this and really can't find a better place to handle this, then remember that JSON is just a string, and all the tools for string manipulation can be brought to bear on this problem. So you could do something like:
var myObj = {
id: "89074987798719283473" // <-- String within javascript
}
var json = JSON.stringify(myObj); // this is {"id":"89074987798719283473"}
var numberJson = json.replace(/"id":"(\d+)"/,'"id":$1'); // this is now {"id":89074987798719283473}
console.log(numberJson);
Of course this is hacky and error prone as you have to be very careful about what you are matching (you might have other properties called id nested in your json that you don't want manipulated). If you wanted to make it a little more robust, you could append something the end of your id before you stringify to make it easier to find and replace it in the string.

Variable in JSON

I don't have much experience with JSON, I want to know if something like this is possible.
{
"variable": "A really long value that will take up a lot of space if repeated",
"array": [variable, variable, variable]
}
Obviously that isn't valid, but I want to know if there is a way to do this. I tried using "variable" but of course that just sets the array item to the string "variable". The reason I want to do this is I need to repeat long values in a multidimensional array, which takes up a lot of space.
Thanks.
If you are willing to do some post-processing on the JSON after parsing it, then you can use a token value in your array, and replace the token after parsing with the variable. Example:
{
"variable": "A really long value",
"array": ["variable", "variable", "variable"]
}
Then, in your code that parses:
var obj = JSON.parse(str);
for (var i=0; i<obj.array.length; i++)
{
obj.array[i] = obj[obj.array[i]];
}
Are you worried about space in the output, or in the object created from the JSON? In the latter case, it's likely that the string values will be coalesced when the parsing happens.
If you're concerned about the size of the JSON, then you'll probably either want to change to another format, or de-duplicate the strings in the JSON.
You could add an object to your JSON data that maps ID numbers to strings, then use the IDs to represent te strings.
There is no way to do this in pure JSON (full spec here).
If you wanted to do something like that you might want to look into templating tools such as Handlebars
you will get your answer here jason tutorial for beginners
example:
var data={
"firstName":"Ray",
"lastName":"Villalobos",
"joined":2012
};

accessing JSON array item from another array

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.

Categories