Syntax Error In Javascript Object Declaration - javascript

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'];

Related

What happens when same key is defined more than once with different values in an object

This is a question about Javascript(and possibly other languages) fundamentals.
I was developing a project and at some point a realized I had defined the same key more than once in an object but no error appeared on console. After some research I couldn't find a clear/official statement to what happens in this situation or how this affects the program. All I could find out is the output in a simple example:
let obj = {key1:1, key1:2, key1:3};
console.log(obj.key1);// >> output = 3
console.log(Object.keys(obj));// >> output = ['key1']
My question is: The value is just redefined and all previous declarations are erased? Is this a limitation or some kind of error of Javascript?
The value is just redefined and all previous declarations are erased?
Yes. When an object literal contains duplicate keys, only the final key in the object literal will exist on the object after the object is evaluated.
Is this a limitation or some kind of error of Javascript?
It's permitted, but it's nonsense. Like lots of things in programming, there are things which are syntactically allowed but don't make any sense in code.
But you can use a linter to prevent from making these sorts of mistakes, eg ESLint's no-dupe-keys.
There's one case where something very similar to duplicate keys can be common, which is when using object spread, eg:
const obj = { foo: 'foo', bar: 'bar' };
// Now say we want to create a new object containing the properties of `obj`
// plus an updated value for `foo`:
const newObj = { ...obj, foo: 'newFoo' }
This sort of approach is very common when working with data structures immutably, like in React. It's not exactly the same thing as an outright duplicate key in the source code, but it's interpreted the same way - whatever value gets interpreted last in the key-value list (regardless of if the key is spread or static) will be the value that the final object contains at that key.

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

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.

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

Name Indexes in Javascript - Array / Object?

I understand that when index names are used to push values in Javascript, they essentially work like objects. But what I don't understand is the following behaviour -
person = [];
person[0] = "Someone";
person["test"] = "SomeoneElse"
Inputting person on the console prints ["Someone"] and I could see no information about person.test.
person.test does print SomeoneElse. However, if I go console.log(person), I get ["Someone", test: "SomeoneElse"].
Curious to check if this makes sense, I tried to create a structure like this one -
var experiment = ["Someone1", test1: "SomeoneElse1"]
and what I get is
Uncaught SyntaxError: Unexpected token
What am I missing?
Thanks in advance!
Typing person on the console prints ["Someone"].
Array.prototype.toString formats this output, and it only considers the "array values" of itself without other properties.
However, if I go console.log(person), I get ["Someone", test: "SomeoneElse"].
console.log outputs other information about the object, including own properties.
Uncaught SyntaxError: Unexpected token
Because that is bogus syntax; the array literal syntax doesn't allow keys, because array values aren't supposed to have keys. Arrays are a numerically indexed list of values. Merely by the fact that under the hood those lists are implemented using objects (because everything in Javascript is an object of some kind or another) are you able to set "non numeric keys" on the array. That doesn't mean you're using the array correctly though.
Also see Are JavaScript Array elements nothing more than Array object properties?
This is because an array in JavaScript is also an object itself, and objects can have properties. So it is perfectly valid to have an array with elements, but also have properties set on the array object.
The second example doesn't work because the [...,...,...] syntax is specifically for instantiating an array and its elements.
typing person in console is like having an alert(person); or passing its value to a variable or element, so it is more like you want to get the first set of readable values. That is the reason why it is showing you the values inside, you can try adding person[1] = *something;*, then it will display someone, something
console.log(person) - it displays all the items inside an object. It is more like informing you of what is inside, like a text visualizer in your IDE
var experiment = ["Someone1", test1: "SomeoneElse1"] - it will absolutely throw an exception there is no such format like this on initializing values, at least it is expecting an array format like var experiment = ["Someone1", "SomeoneElse1"]

How can I prevent extra array elements being created in Javascript?

In PHP, if you do this
$var = array();
$var[5000] = 1;
echo count($var);
It prints 1.
In JS it makes the "missing" elements.
<script type="text/javascript">
var fred = [];
fred[10] = 1;
alert(fred.length);
</script>
Alerts "11".
Can I prevent this? Is it good for anything? I'm a PHP coder trying to adapt to Javascript.
EDIT:
I'm working on an app that uses Google Maps v2 and markerManager. The code has been working for ages, but a problem has suddenly arisen in Chrome (17.0.963.56 m) where markers seem to be duplicated (or more) and then rendering moved markers goes completely wrong, often followed by a browser freeze-up. Looking in the DOM using Firebug, I found gazillions of "undefined" elements in arrays under the grid_ variable in markerManager. I figured that, if I could remove these, I might have slicker code, whether it fixes the marker problem or not. Thanks.
As a PHP coder, you're accustomed to array keys being fairly arbitrary. In JavaScript however, if you assign an array element numerically that doesn't exist, the array will be allocated with empty elements up to the one you created. That's the behavior you found. Objects, on the other hand, denoted by {} rather than [], accept arbitrary property names (with caution) and function a little more closely to how you're accustomed PHP's array structures functioning. This is not to say that JavaScript objects (or object literals) are a direct analogue to PHP arrays....
If what you want is a data structure with a key called "10", that is a job for an object literal (though it isn't great practice to name object properties numerically.
var fred = {};
fred["10"] = 1;
Note, the more normal syntax of dealing with an object literal is the object.property notation, but that is not valid for numeric properties:
// name as a property
fred.name = "fred";
// Syntax error...
fred.10 = 10;
// Use [] notation for numeric properties:
fred["10"] = 10;
Object literals do not have a length property, however. So you cannot do:
fred.length;
// undefined
You may use an object instead of an array, but you loose some of the benefits of an array, like access to a length property.
<script type="text/javascript">
var fred = {};
fred['10'] = 1;
// alert(fred.length); // won't work anymore
</script>
On the other hand no extra entries will be generated and the access to a specific value works almost the same way as in an array. If you want to traverse all values, use the following:
for( var el in fred ) {
if ( fred.hasOwnProperty( el ) ) {
alert( fred[ el ] );
}
}

Categories