How to find if a string appears anywhere in an object? - javascript

I have several objects. They are structured many different ways. For example:
var obj1 = {
'key1':'value',
'key2':[{
'somekey':'somevalue',
'nestedObject': [{
'something':'{{THIS STRING}}'
}]
}]
}
var obj2 = {
'key5':'some text {{THIS STRING}} some more text',
'name':[{
'somekey':'somevalue'
}]
}
There are many more objects than this, and their structures can be infinitely different.
I am looking for a way to find {{THIS STRING}}, no matter where it appears in the object, and no matter what other text surrounds it. All I need to know is a true/false of if it appears anywhere at all in the values of any given object, regardless of how deeply-nested in the object it is.
Thank you!

Note: This is a quick method indeed, but it does not work for all use cases. e.g. if your keys may contain the desired string, this will give wrong output. See comments below.
Not the cleanest of solutions, but you can turn your object into a JSON string using JSON.stringify(), and then look for the string you want inside that string.
var obj1_str = JSON.stringify(obj1);
var isInFile = obj1_str.includes("your_string"); //true if your string is there, false otherwise.

Related

How to slice value out of array in JS

I am trying to isolate the first value from an array that is constructed like below using JS:
[john,mike,tom]
I have tried the slice method but it is not working and I am assuming it's the way the array is constructed where the strings aren't enclosed in quotes. What would be the best way to transform the array above to either a string as a whole or a more properly formatted array so I can pull out any value I want?
edit For additional context, the array I mentioned above is the way is being passed to me from the source. I am trying to figure out how I can work with it to be able to slice up the values.
Sorry for the layman presentation of my question but I am still quite the beginner in JS and would appreciate it if anyone could help me out. Thanks!
In javascript, strings are enclosed in quotes. e.g.
'john', "mike" ect. so in order to create an array/list you need to put these values with quotes inside array and then access using index e.g.
var array = ['john', 'mike', 'tom']
console.log(array[0]); // john
Why do you need the strings to not have quotes? Is there an specific reason?
In js you need to put quotes on strings. If you try for example declaring an array in the way you did above the following will happen:
let x = [janaina,joao,julia]
VM203:1 Uncaught ReferenceError: janaina is not defined
at :1:10
So, correct way to delcare your array:
let x = ['janaina','joao','julia']
Now slice will work:
x.slice(0,1);
The result will be:
['janaina']
You can use the array prototype .shift(), but it will mutate your original array.
const john = {x: 124};
const mike = {x: 333};
const tom = {y: 355};
const slicy = [john, mike, tom].shift();
console.log(slicy);

Default field values in nested objects

I am attempting to create an object from JSON.
Part of my object looks like
a: {
name: "A name",
b: {
c: {
d: []
}
}
}
To save bandwidth, empty arrays and empty objects are stripped from the JSON, so the JSON that I receive is
{ "a": { "name": "A name" }}
If I just convert the JSON to an object, this leads to errors when I try to do things like a.b.c.d.length, as undefined does not have a length.
At the moment, I am populating the missing fields by something like
const json = getJson();
const obj = {
...json,
a: {
...json.a,
b: {
...json.a.b,
c: {
...json.a.b.c,
d: json.a.b.c.d || []
}
}
}
};
This is pretty verbose, and is going to get even uglier when there are several fields that need default values.
One obvious solution is to not strip out the empty arrays from the transmitted JSON. Assuming that that is not possible, is there a better way to handle this case?
In the real case, there are multiple fields at each level, so all of the spread operators are necessary. (Even if they were not, I would want to include them as the structure is likely to grow in the future.)
Edit: I am not using JQuery. I am using whatwg-fetch to retrieve data.
I would suggest some sort of solution in which you establish a pre-determined schema, and continue to omit empty arrays/values. You can then do something like
_.get(object, 'property.path.here', defaultValue)
with lodash.get(), where defaultValue is determined by your schema as an empty string "", 0, null, etc.
Removing empty objects/arrays from response is not a good practice, because these can be valid values.
It is premature optimization, which does not have real benefit on performance. In return it will give you a lot of headaches when you will need to specially handle each response.
But if you still think that it is worth, then I recommend lodash get function.
_.get(object, 'property.path.here')
For best practice, I think you should not employ sophisticated approach or syntax.
Just use a common default value set of Javascript:
var _d = a.b.c.d || [].
// does something with _d.length
While you are trying to do something, you can achieve that but code quality is worse. Think different and do different it may be better.
Moreover, I think declare the original a object explicitly with all properties is better than remove empty property like you do.

JSON.stringify turned the value array into a string

I have a JS object
{
aString:[aNumber, aURL]
}
JSON.stringify() returns
{
"aString":"[number, \"aURL\"]"
}
I thought that valid JSON can have arrays as values. Can I have stringify return the JSON string without converting the array into a string? Basically I need turn the whole JS object straight into a string, without any modification.
Is there a better way to do this? I've been looking around but everyone suggests using JSON.stringify if I want an object to string, and no one has raised this problem.
EDIT: Thanks for the quick responses. Here is how I created my JS object, please let me know if I messed up and how!
cookie = {};
// productURL is a string, timer is a number, imageSrc is a URL string
cookie[productURL] = [timer, imageSrc];
// then, I just stringified cookie
newCookie = JSON.stringify(cookie);
If it is also relevant, I am setting an actual cookie's value as the resulting JSON string, in order to access it in another set of functions. Setting the cookie's value does do some URI encoding of its own, but I've actually been grabbing the value of newCookie in the Chrome console as well and it also returns the Array as a string.
If an object you're trying to stringify has a toJSON function, that will be called by JSON.stringify. Most likely you have an external library that's adding Array.prototype.toJSON.
For example, an old version (1.6) of Prototype JS will "conveniently" add that for you.
Prototype 1.6.1:
alert(JSON.stringify([1, 2, 3]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.6.1/prototype.min.js"></script>
Whereas a newer version will not.
Prototype 1.7.2:
alert(JSON.stringify([1, 2, 3]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.min.js"></script>
You could try deleting Array.prototype.toJSON just to see if that's what's causing the problem. If it is, you might want to look into upgrading/deprecating any libraries in your code that do weird things like that.
Prototype 1.6.1 (after deleting toJSON)
delete Array.prototype.toJSON;
alert(JSON.stringify([1, 2, 3]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.6.1/prototype.min.js"></script>
Based on your description this is not what should happen.
If you have code like this:
var obj = {
aString:[123, "test"]
}
document.getElementById("out").value = JSON.stringify(obj);
it will generate the expected json:
{"aString":[123,"test"]}
also see https://jsfiddle.net/zudrrc13/
in order to produce your output the original object would have to look something like:
var obj = {
aString:"[123, \"test\"]"
}

Syntax Error In Javascript Object Declaration

I have declared an object like this
var me = {'alex','moore','baby','you'};
without the property names. I just want the elements to be set of strings. But i get error in both chrome dev-tools and firebug. i have googled but can't find any good answer.
What am i doing wrong?
thanks.
EDIT
Thanks for your answers. The reason am asking is that i am reading a book "Javascript: The Definitive Guide". On page 115 of the PDF file, it states that Javascript Objects ::
"They can also be used
(by ignoring the value part of the string-to-value mapping)
to represent sets of strings."
So i was trying to test it but getting errors. It seems the book is wrong that they can be used to represent sets of strings.
If you want an ordered list of values, then use an array ([]), not a plain object ({}).
var me = ['alex','moore','baby','you'];
Objects must have named properties.
var me = {
foo: 'alex',
bar: 'moore',
baz: 'baby',
etc: 'you'
};
Seems like what you are looking for is an array
var me = ['alex','moore','baby','you'];
Objects on the other hand need to have properties defined.
Square brackets
var me = ['alex','moore','baby','you'];
You should be using array not object.
var me = ['alex','moore','baby','you'];

what is the difference here in this use of JSON.stringify()?

what is the difference in the following between the result of p and q and why would you do either way, which is best?
var my = [
{"a":"sdsds"},
{"b":"sdsds"},
{"c":"sdsds"},
{"d":"sdsds"},
{"e":"sdsds"}
];
var p = JSON.stringify({ "myText": my };);
var q = { "myText": JSON.stringify(my) };
p is a string containing:
'{"myText":[{"a":"sdsds"},{"b":"sdsds"},{"c":"sdsds"},{"d":"sdsds"},{"e":"sdsds"}]}'
q is an object:
{
myText: '[{"a":"sdsds"},{"b":"sdsds"},{"c":"sdsds"},{"d":"sdsds"},{"e":"sdsds"}]'
}
They're not the same thing, so I can't tell you which is best. What do you want to use it for?
p is a string that looks like "{ \"mytext\": ... }".
q is an object with a property called mytext.
One creates a JSON text consisting of an object with the property 'myText' with the value being the data that 'my' contains (i.e. an array of objects each of which has one property/string pair).
The other creates an object consisting of a property 'myText' with the value being a string containing a JSON text built from the data in 'my'.
why would you do either way
The former is generally the approach taken when creating JSON.
That latter might be useful if you planned to pass the object to something like jQuery's data property in an .ajax() call.
which is best
Neither. They simply different. "Best" is whatever works for what you are going to do with the variables.

Categories