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.
Related
I'm trying to generate a JSON string which will contain all of my filters, but I constantly stuck with duplicate keys. So, I want to find a solution that turns the duplicate keys into a JSON array.
For example, I have this JSON object:
{
"filter-1": "value-1",
"filter-1": "value-2",
"filter-2": "value-3",
"filter-3": "value-4"
}
And I want to turn it into this:
{
"filter-1": ["value-1", "value-2"],
"filter-2": "value-3",
"filter-3": "value-4"
}
Can someone point me in the right direction? I would appreciate solutions in JavaScript but any method would be more than welcome! Thanks in advance!
The duplicate key-pairs are causing overwrite issues.
Javascript objects doesn't allow duplicate keys.
var testObj = JSON.parse('{"filter-1":"value-1","filter-1":"value-2","filter-2":"value-3","filter-3":"value-4"}'); will overwrite the first key-pair (filter-1: value-1) when it parses the second key-pair (filter1: value-2) since both key-pairs have the same key.
However, JSON specification (not Javscript objects) does not specifically mention whether duplicate keys are allowed or not. You may wish to write your own parsing function to handle the duplicate keys.
You will have to change the format of your JSON since keys in JS objects must be unique.
Then you can hard coded or use libraries like jquery or underscorejs to group them out.
https://jsfiddle.net/p5fkjcwt/1/
var objects =
{
0: {"filter": "filter-1", "value":"value-1"},
1: {"filter": "filter-1", "value":"value-2"},
2: {"filter": "filter-2", "value":"value-3"},
3: {"filter": "filter-3", "value":"value-4"}
}
var result = _.groupBy(objects,"filter")
console.log(result)
I am new to jquery and trying something and got stuck at it,
My problem is i have object with array in it i am not able to find the way to access that array from the object
//My object is shown in debugging time is as below
cache:object
0001-:Array[2]
0:value1,
1:value2
_prto_:object
and i want to access the value1 and value2 from the 0001- array from that object is there way to access that array. Any help would be great. I know with $.each i can loop through it and and then again access the array but is there any other way to do it.
You can access it like, and keep in mind that you should use bracket notation in this context, since your keys having a starting character as a number.
cache['0001-'][0] //first element on that array
cache['0001-'][1] //second element
A workaround for your new requirement,
var cache = {'0001-' : [0,1]};
var xKeys = Object.keys(cache);
console.log(xObj[xKeys[0]][0]);
console.log(xObj[xKeys[0]][1]);
My question is the following, in an array:
var array = new Array();
array['abc'] = 'value1';
array['def'] = 'value2';
How do I get the associative key of an array if I have its index number? Let's say I want associative key of arr[0]'s associative key ( => 'abc'), or associative key of arr[1] '=> 'def'). How is this possible in jQuery?
Let's be clear, I am not looking for the value and I do not need to use $.each(). I just need to link 0 to 'abc' and 1 => 'def' etc... Unfortunately something like arr[0].assoc_key() doesn't seem to exist T_T
Thanks a bunch.
All right so the solution is pretty simple, you need to create an object which associates indeces with keys as well as keys with values. Here is a JSBin that works. Please note that to add an element, you need a custom function (addElement in this case) to be able to have both indeces and keys associated at the right places. This is a rough draft to give you an idea of how it can be done!
JSBin
If you have any question or if that wasn't exactly what you expected, simply edit your question and I'll have another glance at it. It HAS to be a custom made object if you want the behavior you asked for.
Javascript doesn't have a native Dictionary type, you would have to write it. – T McKeown
It isn't possible and jQuery doesn't come into the picture at all. If you use an array as a dictionary like that, you are doing something wrong. – Jon
rethink the way you are doing it. Maybe try array[0] = {key: 'abc', value: 'value1'} – Geezer68
#Geezer68, objects do not support multidimentional data, the array I'm working on is 3 levels deep (I know I didn't says so in my original post, but I didn't think it was relevant).
Anyway, thank you guys, it answers the question! I will rethink it then ;-)
EDIT: I guess I'll just add a level:
var array = new Array();
array[] = 'abc';
array[0] = 'value1'
I don't know an other than using a for ... in. So here how i do it and hope you get a better answer (because i want to know aswell!).
var array = new Array();
array['abc'] = 'value1';
array['def'] = 'value2';
var listKeys = [];
for(x in array) listKeys.push(x);
console.log(listKeys); // ['abc', 'def']
but using [string] on an array object is adding property to the object, not the array. So it may be better to initialise it like that :
var array = {};
You might learn more information on this technique in this question and some restriction on why you should not rely on that.
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.
I have a javascript associative array like one below
var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
I want to convert it using Stringify to json object. I want to know after conversion how the json object will look like.
Also when i have this object How I can convert it back to associative array again.
First of all, by making my_cars an array and stringifying it, you don't get what you expect.
var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
alert(JSON.stringify(my_cars));
This alerts [].
What you want is to start with {}:
var my_cars= {};
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
alert(JSON.stringify(my_cars));
This alerts
{"cool":"Mustang","family":"Station Wagon","big":"SUV"}
To get your object back from the string, use JSON.parse().
var s = JSON.stringify(my_cars);
var c = JSON.parse(s);
alert(c.cool);
This alerts "Mustang".
See http://jsfiddle.net/Y2De9/
No,But the user want to use array not json.
Normal JavaScript arrays are designed to hold data with numeric indexes. You can stuff named keys on to them (and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for. The JSON array data type cannot have named keys on an array.
If you want named keys, use an Object, not an Array.
*source
var test = []; // Object
test[0] = 'test'; //this will be stringified
Now if you want key value pair inside the array
test[1] = {}; // Array
test[1]['b']='item';
var json = JSON.stringify(test);
output
"["test",{"b":"item"}]"
so you can use an index with array,so alternatively
var my_cars= [];
my_cars[0]={};
my_cars[0]["cool"]="Mustang";
my_cars[1]={};
my_cars[1]["family"]="Station Wagon";
my_cars[2]={};
my_cars[2]["big"]="SUV";
console.log(JSON.stringify(my_cars));
Output
"[{"cool":"Mustang"},{"family":"Station Wagon"},{"big":"SUV"}]"
Moving my comment into an answer so I can show you a code example.
These types of array are no-no's in javascript. You should ONLY use an object for non-numeric keys like this. Array indexes should be numbers. Javascript objects can use arbitrary values for keys (like in your example). Arrays happen to "appear" to work because Arrays themselves are objects, but you will not find normal Array methods will work on them. For example, look at this code example.
var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
alert(my_cars.length); // alerts 0
You have only added properties to the underlying object, not actually added elements to the Array. You should use an Object for this, not an Array. Javascript does not actually have an Associative Array. It has an Object who's properties can often be used like one would use an Associate Array in other languages. But, it's an Object, not an Array.
"JavaScript does not support arrays with named indexes"
The most close state to an associative array is an array with entries converted to properties (as in your case), so I provide a solution for this exact case.
The fun thing is that Chrome's console makes it feel like an associative array: ["cool":"Mustang", "family":"Station Wagon", "big":"SUV"] (Check with F12)
NOTE: open browser's console before running the snippet
var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
let toAssociative=(keys, values)=>
values.reduce((acc, cv)=>{
acc[acc.shift()]=cv
return acc;
}, keys)
let fromAssociative = (assArr)=>({...assArr})
let serialized = JSON.stringify(fromAssociative(my_cars))
let o = JSON.parse(serialized)
let restored = toAssociative(Object.keys(o) , Object.values(o))
//NOTE: Look at the browser's console before executing (not SO console)
console.log("orig:",my_cars)
//[cool: "Mustang", family: "Station Wagon", big: "SUV"]
console.log("serialized:",serialized)
//{"cool":"Mustang","family":"Station Wagon","big":"SUV"}
console.log("restored:",restored) //NOTE: look at the browser's console (F12)
//[cool: "Mustang", family: "Station Wagon", big: "SUV"]
If for some reason you cannot convert your array into object, for instance you are working on a big framework or legacy code that you dont want to touch and your job is only to add som feature which requires JSON API use, you should consider using JSON.stringify(json,function(k,v){}) version of the API.
In the function you can now decide what to do with value of key is of a specific type.