Read and loop through an object with non-unique key value pairs - javascript

I have an object which contains some key/value pairs. When there is a key/value pair that shares the same key as another key/value pair, the first one is not recognised when I console log the object.
For example:
var test = {
"same" : 'Value1',
"same" : 'Value2',
"different" : 'Value3'
};
console.log(test);
Results in the console as:
Object { same="Value2", different="Value3"}
Is it not possible to read an object that has similar key names?
I am trying to loop through the object using this method (How do I loop through or enumerate a JavaScript object?) but I can only ever retrieve one the key/value pairs that share a key.

An object can not have duplicate keys.
So the reason that you can't read the duplicate keys from the object, is that they were never added as two items in the object in the first place. One of the items will simply overwrite the other.

Could you change the structure of the JSON if needed? JSON objects cannot have duplicate keys. Think of it as a hashmap or dictionary. Depending on the language and JSON parser you may also get an exception (not in Javascript though)
In your example above either change it so that you have unique keys or change ti to an array of values like:
var test = {
"same" : ['Value1', 'Value2']
"different" : 'Value3'
};
console.log(test);

A key is a unique value that uniquely identifies the element within the array/object. So, the answer is no, you can't have two elements with the same key value.

Related

In javascript how to replace elements of an array to it's corresponding values in another object?

I have the mapping of abbreviation and full name as follow:
object = {"TSLA":"TESLA INC.","GOOG":"GOOGLE INC.","APPL":"APPLE INC.","AMZN":"AMAZON CORPORATION", "MSFT":"MICROSOFT CORPORATION"}
as an output of function i get the following array:
array = ["AMZN","APPL"]
I want to display the values of the associated keys as follows:
output_array = ["AMAZON CORPORATION", "APPLE INC."]
Note that, the actual object has more key: value pairs
Using IndexOf() I can replace one value. However, I believe there must be a way of mapping the array elements to replace the values at once.
Since I am new to JS, I would appreciate any suggestion.
array.map(abbr => object[abbr]) does the job; it iterates over the array rather than the object, which is more efficient as the object already is a lookup table with the right keys - you are right, there is no need to use indexOf which uses a linear search.

Use slice on javascript object to loop for all elements except first two?

I have an object of objects and I'd like to use a v-for loop to llop through all the objects except the first two ones, sadly I can't use slice sice it's only for arrays, is it possible to remove the first wo elements of an object using javascript without creating a new object
My object is something like:
{
First: { },
Second: { },
Third: { }
}
I am not that pro in js but first check this url
How to loop through a plain JavaScript object with the objects as members?
this just to get maybe an idea
How can I slice an object in Javascript?
so I will give you a logic where you may get a solution
if you won't get answer from above
when finished from url and get clear understand
create a function where it iterate over objects
from what I suggest
then create a variable =1
if var_inc==1 or var-==2
continue
else
do whatever
then do a for loop to loop over over objects
then do that function
just get the logic maybe you get it..
❤🌷😅
JS objects don't store the order of elements like arrays. In the general case, there is no such thing as order of specific key-value pairs. However, you can iterate through object values using some utility libraries (like underscore https://underscorejs.org/#pairs), or you could just use raw js to do something this:
// this will convert your object to an array of values with arbitrary order
Object.keys(obj).map(key => obj[key])
// this will sort keys alphabetically
Object.keys(obj).sort().map(key => obj[key])
Note that some browsers can retain order of keys when calling Object.keys() but you should not rely on it, because it isn't guaranteed.
I would suggest to just use array of objects to be sure of order like this:
[{ key: "First", value: 1 }, { key: "Second", value: 2}]
If you just want to delete the properties of the objects then you can use delete keyword.
delete Obj['First']
delete Obj['Second']`
This would delete both the keys and object would have only 'Third' key

JavaScript : Printing Dynamic value/data

This is sample JSON I got {"valueofa" : 1234}.To print the value it is something like body.valueofa. However, this valueofa can be anything like apple or something else. So to parse that I object I had tried with ${body}.${value} which isn't working and it's shouldn't be. How can I set the variable with body. So that I can parse the body whatever the value is.
If your object always contains only one key value pair like shown in the question, and you don't care about the key, you can just use Object.values()
console.log(Object.values({"valueofa" : 1234})[0]);
console.log(Object.values({"apple" : 1234})[0]);
The same is true for objects holding multiple key value pairs, Object.values() will return an array of all the values in your object if you omit accessing the first element with [0]
You can access a value of JSON using square brackets.
var value = "valueofa";
body[value];

Get value from Json object with unique key

How do I check if a JSON object have key are duplicate, just get distint the key and not use foreach function? Such as:
var objectData = {[value1: abc], [value1: abc], [value2: bcd]}
If a key doesn't exist, and I try to access it, will it return undefined? Or get the error?
If this is meant to be an array of JSON objects:
var objectData = [ {"value1": "abc"}, {"value1": "abc"}, {"value2": "bcd"} ];
Then your answer lies within the responses to this question: Remove duplicates from an array of objects in javascript or this one Remove duplicate objects from an array using javascript.
If your notation accurately reflects what is produced by your system (or your own coding), you may want to rework it a bit so it makes sense.
Hope that helps.

Iterate over jQuery JSON object in Chrome its changing the order

Jquery + rails 4
In json_data instance i have some data with key and value, The key is an integer id and the value is an object which contains data.However when I try to iterate over this data with the jQuery $.each function, the results come back sorted by the key instead.How can I iterate over my collection of objects in their original order?
$.each(json_data, function(key, value){
console.log(key);
});
key = 6181 30654 39148 30743 30510 42998 5788 30401 ...//Mozilla Working Fine (Right)
key = 5788 6011 6181 30401 30510 30639 30654 30698 30743 ...// Chrome Not Working Fine (Wrong)
Regarding "order" in an object:
A JavaScript object is a hash table, and is optimized for constant time lookup of key:value pairs.
Arrays are a data structure in which the elements are assigned to a discrete index value. When you iterate over the elements of an array, you will return a predictable pattern that matches the order of the items in the array.
In an object however, there are no index values, so there is no constant predictable way to iterate over it in order. The object just stores key:value pairs that are optimized for constant-time lookup.
EDIT: I will demonstrate those two methods of iterating just for illustration, but I wanted to warn you in advance, they won't change the fact that you won't get the keys returned in a consistent order.
var json_data = {6181:true, 30654:true, 39148:true, 30743:true, 30510:true, 42998:true, 5788:true, 30401:true};
for(item in json_data){
console.log(item);
} // *might* return a different order based on browser or JavaScript implementation
Clarifying one more time: objects are not associated with a particular 'order'. They are optimized to provide "constant time" lookup. Regardless of the size of the object, if you query a key, the associated value will be returned to you in constant time.
If you need to impose a particular order, you will need to use an array.
Example:
var json_data = [6181, 30654, 39148, 30743, 30510, 42998, 5788, 30401];
for(var i = 0; i < json_data.length; i++){
console.log(json_data[i]);
}
// always returns the values in the same order they are in the json_data array.
// changing the order in the array will change the order they are output and
// and that order will be the same regardless of which browser or version of JavaScript you
// are using.

Categories

Resources