I am trying to apply the jQuery $.unique() function to an array of objects. I enjoy using this function with an array of primative variables but apparently it doesn't work with objects, as seen here: http://jsfiddle.net/abs10gxo/
var arr1 = [
"aaa",
"bbb",
"aaa"
];
console.log($.unique(arr1)); // Works as expected.
var arr2 = [
{ "a": "aaa" },
{ "b": "bbb" },
{ "a": "aaa" }
];
console.log($.unique(arr2)); // Doesn't work as expected.
I can't seem to find any literature on jQuery.com in regard to using this function with an array of objects; it only adheres to primative types. Can anyone recommend a solution? Library or custom are both welcome answers. I am familiar with doing this in C++ where you can overload the comparative == sign operator but not sure if that is the best approach since I am using jQuery.
Related
I've already tried to find a solution on stack, but I didn't found a possible reply, so I decided to open a topic to ask:
Let's say we have 2 arrays: one containing "keys" and another one containing "values"
Example:
keys = [CO2, Blood, General, AnotherKey, ... ]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[... [
I have to create a Json with a specific structure like:
[{
name: 'CO2',
data: [2,5,4,6]
}, {
name: 'Blood',
data: [4,5,6]
}, {
name: 'General',
data: [1,3,34.5,43.4]
}, {
...
},
}]
I've tried to make some test bymyself, like concatenate strings and then encode it as json, but I don't think is the correct path to follow and a good implementation of it ... I've also take a look on JSON.PARSE, JSON.stringify, but I never arrived at good solution so... I am asking if someone know the correct way to implements it!
EDIT:
In reality, i didn't find a solution since "name" and "data" are no strings but object
Here's one way to get your desired output:
keys = ["CO2", "Blood", "General", "AnotherKey"]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ]
const output = keys.map((x, i) => {
return {"name": x, "data": values[i]}
})
console.log(output)
However, since you're literally constructing key/value pairs, you should consider whether an object might be a better data format to output:
keys = ["CO2", "Blood", "General", "AnotherKey"]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ]
const output = {}
for (let i=0; i<keys.length; i++) {
output[keys[i]] = values[i]
}
console.log(output)
With this data structure you can easily get the data for any keyword (e.g. output.CO2). With your array structure you would need to iterate over the array every time you wanted to find something in it.
(Note: The reason you weren't getting anywhere useful by searching for JSON methods is that nothing in your question has anything to do with JSON; you're just trying to transform some data from one format to another. JSON is a string representation of a data object.)
I have recently gotten into javascript (about four days ago), and I'm having troubles acclimating to the syntax a little bit. I'm creating a calender of sorts and I'm trying to get an array of objects (one for each month) to be declared within my "main" object, the calender. I have done copious amounts of googling and browsed all over W3Schools and can't seem to figure it out. So if I have
var calender = {
:
:...functions{},
months: [],
How would I go about getting objects inside of months and declaring their properties (i.e. months[0] would have a name of "January" and its number of days etc)? I am at a conceptual standstill. Do I accomplish this index by index, or can I just literally declare the objects at array creation? From what I grasped so far, it would seem normally I could just say something like var arr = {varName: "name",...(and so on)}, but it seems doing that in the brackets is not allowed, and I'm not sure syntactically where I access the indices. Or maybe I'm just doing this utterly bass ackwards. Any guidance would be greatly appreciated. Thanks
One way; object literals within an array:
var calendar = {
months: [
{
name : "Jan",
days : 31
},
{
name : "Feb",
days : "28ish"
}
]
};
alert( calendar.months[0].days );
Let's get back to basics, this is how you can write literal objects, arrays and objects containing arrays containing objects that contain arrays:
var my_object = {key1: "value1", key2: "value2"};
console.log(my_object.key1);
var my_array = ["value1", "value2"];
console.log(my_array[0]);
var my_compound = {a: [{b: "c", d: [0, 1, 2]},
{b: "e", d: [3, 4, 5]}]};
console.log(my_compound.a[1].d[0]); // => 3
console.log(my_compound["a"][1]["d"][0]); // same thing, perhaps more readable?
I have some data which I originally stored in a generic Javascript object, with the ID as a key:
{
"7": {"id":"7","name":"Hello"},
"3": {"id":"3","name":"World"},
...
}
However, I discovered that browsers do not guarantee a particular object order when looping through them, so in the above "3" would come before "7". I switched to using an array format like this:
[
{"id":"7","name":"Hello"},
{"id":"3","name":"World"},
...
]
Now, I can loop in the correct order but cannot do fast lookups, e.g. data["3"] without having to loop through the array.
Is there a good way to combine both approaches? I would rather avoid using a separate object for each format, because the object is pretty large (hundreds of elements).
I have run across this problem as well. A solution is to keep an ordered array of keys in addition to the original object.
var objects = {
"7": {"id":"7","name":"Hello"},
"3": {"id":"3","name":"World"},
...
}
var order = [ "3", "7", ... ];
Now if you want the second element you can do this lookup:
var second_object = objects[order[1]];
The ECMA standard does not say anything about the order of the elements in an object. And specifically Chrome reorders the keys when they look like numbers.
Example:
var example = {
"a": "a",
"b": "b",
"1": "1",
"2": "2"
};
if you print this in Chrome will get something like:
{
1: "1",
2: "2",
"a": "a",
"b": "b"
};
It's a little sour .. but life.
You could use the solution Andy linked as well, basically wrapping these two together in one object.
An alternative that I use a lot is a custom map function that allows you to specify the order in which the object is traversed. Typically you will do sorting when you're printing your data to the user so while you loop and create your table rows (for instance) your iterator will pass the rows in the order your sort function specifies. I thought it was a nice idea :)
The signature looks like:
function map(object, callback, sort_function);
Example usage:
map(object, function (row) {
table.add_row(row.header, row.value);
}, function (key1, key2) {
return object[key1] - object[key2];
});
Rather than coding your own, there are off-the-shelf libraries available to provide "as provided" JSON parsing or "consistently sorted" JSON printing for display.
You might well consider either of these:
The 'json-order' package offers parsing, formatting & pretty-printing with stable ordering. This is based on having ordered input.
The 'fast-json-stable-stringify' package offers deterministic formatting based on sorting.
What is the most efficient way to filter an JavaScript array of objects based on a key-value?
For example: I'd like to select items by color in the following array:
[{Id:1, color:"blue"},{Id:2, color:"green"},{Id:3, color:"blue"},{Id:4, color:"red"}]
There's an easy syntax for selecting items by property in languages like CSS or xslt, but I can't find an equivalent for JSON.
You can't filter JSON strings directly -- with ease, at least -- without first parsing them into JavaScript objects:
var collection = JSON.parse(jsonString);
But note that JSON parsers are normally strict -- object keys must be strings (http://json.org):
[{ "Id": 1, "color": "blue" }, { "Id": 2, "color": "green" }, ...]
After that, you can use filter on the returned Array:
var filtered = collection.filter(function (item) {
return item.color === "blue";
});
console.log(filtered[0]); // [Object] :: { Id: 1, color: "blue" }
To support older browsers, include json2.js for JSON.parse along with the "Compatibility" code offered by MDN for filter (or use the ES5-shim for a collection of such definitions).
JSON is not a language. I assume you mean javascript. And you will have to write it yourself there is no built in way.
I have some data which I originally stored in a generic Javascript object, with the ID as a key:
{
"7": {"id":"7","name":"Hello"},
"3": {"id":"3","name":"World"},
...
}
However, I discovered that browsers do not guarantee a particular object order when looping through them, so in the above "3" would come before "7". I switched to using an array format like this:
[
{"id":"7","name":"Hello"},
{"id":"3","name":"World"},
...
]
Now, I can loop in the correct order but cannot do fast lookups, e.g. data["3"] without having to loop through the array.
Is there a good way to combine both approaches? I would rather avoid using a separate object for each format, because the object is pretty large (hundreds of elements).
I have run across this problem as well. A solution is to keep an ordered array of keys in addition to the original object.
var objects = {
"7": {"id":"7","name":"Hello"},
"3": {"id":"3","name":"World"},
...
}
var order = [ "3", "7", ... ];
Now if you want the second element you can do this lookup:
var second_object = objects[order[1]];
The ECMA standard does not say anything about the order of the elements in an object. And specifically Chrome reorders the keys when they look like numbers.
Example:
var example = {
"a": "a",
"b": "b",
"1": "1",
"2": "2"
};
if you print this in Chrome will get something like:
{
1: "1",
2: "2",
"a": "a",
"b": "b"
};
It's a little sour .. but life.
You could use the solution Andy linked as well, basically wrapping these two together in one object.
An alternative that I use a lot is a custom map function that allows you to specify the order in which the object is traversed. Typically you will do sorting when you're printing your data to the user so while you loop and create your table rows (for instance) your iterator will pass the rows in the order your sort function specifies. I thought it was a nice idea :)
The signature looks like:
function map(object, callback, sort_function);
Example usage:
map(object, function (row) {
table.add_row(row.header, row.value);
}, function (key1, key2) {
return object[key1] - object[key2];
});
Rather than coding your own, there are off-the-shelf libraries available to provide "as provided" JSON parsing or "consistently sorted" JSON printing for display.
You might well consider either of these:
The 'json-order' package offers parsing, formatting & pretty-printing with stable ordering. This is based on having ordered input.
The 'fast-json-stable-stringify' package offers deterministic formatting based on sorting.