how to get groupBy() but in other outcome in javascript - javascript

I was looking this sandbox
And basically it does what I want but I want in parent element (which is grouped by for) to add property name.
Also, I want to reduce some properties in below, like to remove color in child elements, because I grouped by color?
For example, with my data json looks like:
"stuff": {
"onetype": [
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
],
"othertype": {"id":2,"company":"ACME"}
},
"otherstuff": {
"thing": [[1,42],[2,2]]
}
or other approach:
I have an array with one-to many key relation:
[1,1]
[1,2]
[2,2]
[3,2]
[4,1]
How to convert to valid json, with one property in root (first element from an array), and its depended children?

Related

VueJS - Filtering array of objects and comparing the $route.params with the property value

I am trying to sort the arrays using JavaScript such a way that i want to display the property values only when it is equal to the $route.params.my_id.
Here is my response that i get from the API ie Array of objects:
[
{
"my_id": 2, <-- index[0]
"employee_name": "John",
"salary: "26000",
"experience: "5"
},
{
"my_id": 3, <-- index[1]
"employee_name": "Sam",
"salary: "46000",
"experience: "15"
},
{
"my_id": 1, <-- index[2]
"employee_name": "Raj",
"salary: "16000",
"experience: null
}
]
In component1 i am setting the $route.params.my_id = company.my_id.toString() where the company.my_id is taken from the response of API. So, the company.my_id gets 1, 2 or 3 respectively depending on the selected route.
In component2 i am using company[$route.params.my_id].employee_name as a option for select button. Here i have used $route.params.my_id as the index value so it can 1, 2 or 3.
But here is the question, the index starts from zero, so it is [0], [1] or [2]. So if $route.params.my_id is 2 then in component2 company[2].employee_name it should show the my_id 2's information but rather it shows my_id 1's info as index[2] contains my_id 1's info.
Do not rely on sorting to achieve this
It was a clever idea, but it will only work well if the my_id values form a good sequence, i.e. always consisting of the integers from 1 (or 0) upwards in some permutation.
Do not rely on this being the case.
It will help you in your debugging if you change the my_id values to something that is nothing like an array index, e.g. "idx", "idy", "idz". This way, when your code breaks, it is much more obvious what is going wrong.
Filter the array, rather than sorting it
You could try this, inside the .then( result => { ... })
this.company= result.data.filter(company => company.my_id === $route.params.my_id )[0]
This extracts just the one company entry of interest. Try it out.
Better to do error checking
If the above works in principle, you should improve the code to test for two possible error states. First, there may be no companies matching the id. Secondly, there may be more than one company matching it.
const matchingCompanies = result.data.filter(company => company.my_id === $route.params.my_id )
if (matchingCompanies.length===0){ /* Error action for no matches */}
if (matchingCompanies.length>=2){ /* Error action for multiple matches */}
// Now we know there is exactly one match
const matchingCompany = matchingCompanies[0];

Index on array keypath doesn't find any values

I want to get familiar with indexedDB to built my Firefox WebExtension.
My sample data is structured like this:
const sampleDataRaw = [
{
"ent_seq" : 1413190,
"att1" : [ {
"sub11" : "content1",
"sub12" : [ "word" ]
}, {
"sub11" : "content2"
} ],
"att2" : [ {
"sub21" : "other content",
"sub22" : [ "term" ]
} ]
}, {
"ent_seq" : 1000010,
"att2" : [ {
"sub21" : "more content"
}, {
"sub22" : "more words"
} ]
}
] // end sampleRawData
I got as far as opening/creating my database, adding this sample data and querying it by the ent_seq key using objectStore.get() and objectStore.openCursor().
The problem arises when I want to search the sub11 or sub21 fields using indexes I should have created for these like this:
objectStore.createIndex("sub11Elements", "att1.sub11", { unique: false });
objectStore.createIndex("sub21Elements", "att2.sub21", { unique: false });
When I want to search, say, fields sub11 as here:
var index = objectStore.index("sub11Elements");
index.get("content1").onsuccess = function(event) {
// I should have the first object of my data now, alas the result is undefined instead
};
It certainly does succeed, but the returned value is undefined since the get() didn't actually find anything.
I want to know why it doesn't find the entry and how to make it find it. I figured it might be because the keypath is wrong, but as stated, if I instead search by the key (ent_seq) I can successfully get the result.att1[i].sub11 values.
On mozilla's websites it's stated that keys can be of type string and array (or array within array etc) amongst others, and keypath parts are supposed to be concatenated using dots.
From searching on stackexchange I've so far found that it's not possible to have variable keys inside the keypath, but that shouldn't be the case here anyway.
Therefore, I really don't see what might be causing the search to not find the object inside the database.
It looks like the second level of objects are arrays, not properties of the first level of objects. The . accessor accesses sub properties, not indices of an array.
IDBObjectStore.prototype.get always yields success when there is no error, and is not indicative of whether a match was found.
A bit more on point 1. Look at "att1":[{"sub11" : "content1","sub12" : [ "word" ]}.... Pretend this was was an actual basic JavaScript object. Would you be able to use att1.sub11? No. Because the value of att1 is an array, not an object.

Adding objects to a Set in javascript

I am not sure if there is a set data structure in JS like in python. I have an array of objects like this in Javascript, the ID is unique. If I have two arrays like this - how can I combine them into a single array where I throw away duplicates based on the ID field?
First array:
[{
filed : "1-Jan-1970",
name: "John Smith",
ID: 1234
}
... (many more items)
]
Second array:
[{
filed : "1-Jan-1980",
name: "John Smith",
ID: 1234
}
... (many more items)
]
In the combined array I only want to keep one item with ID = 1234. I dont care which one is thrown away, how do I do this in Javascript that is also fast? I am looking at combining two lists with a couple of thousand items each and I want to keep only one record per ID from either array. Is there a compact way to combine the two arrays into one and then weed out the duplicates?

Javascript, JSON - Create Table

I have a JSON Array like:
[{
"name": "abc", "month":"Jan-15","value":xyz
},{
"name": "bcd", "month":"Jan-15","value":xyz
},{
"name": "abc", "month":"Feb-15","value":xyz
},{
"name": "bcd", "month":"Feb-15","value":xyz
}]
No. of "names" may vary from month to month. But no. of "month" stays the same.
I need to create tabular overview:
Name Jan-15 Feb- 15 ...... Dec-15
abc value value ..... value
bcd value value ..... value
I'm new to Javascript and I really don't know how to get values in right columns and rows. Though I know how to dynamically add rows.
Shall I opted for "pure" solution or is better to check for a framework like e.g. AngularJS ?
Edit: I have extracted "Months" and "Names" from array and I need to do something like: value = check for this particular "name" in array and return corresponding "value".
How do I write this in JS?
It depends on the form of your data object. If you have an array object or a string object you need to use JSON.parse in order to be able to use indices and values.
If yes, then you will need to have JSON.parse(data).name to return your name values.
JSON.parse(data).month for your months and of course JSON.parse(data).value to return the xyz values.
If your data is already a JSON object then you will simply use data.name, data.month and data.value accordingly.
These links might help you get into the basics, follow the syntax and the examples.
http://www.w3schools.com/js/js_json.asp
http://www.w3schools.com/json/json_eval.asp
http://www.json.org/js.html and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Sort nested objects in Array in Javascript

I receive an object from MongoDB request.
Below is a snippet of it:
{
"Kost": "Kost1",
"Name": "Name1",
"inventar": [
{
"data": "A",
"name": "thefirst",
"ean": "802.0165.813",
},
{
"ean": "802.6725.277",
"name": "thesecond",
"data": "B",
},
{
"ean": "570.6761.483",
"name": "thethird",
"data": "C",
},
{
"ean": "570.6764.519",
"name": "thefourth",
"data": "D",
}
]
}
Later, I will create a table in Jade with this code:
table(border='1', cellspacing='3', cellpadding='4')
tr
th(align='center') ean
th(align='center') name
th(align='center') data
each obj in inventar
tr
each val in obj
td= val
The problem is, that the objects in the Array "inventar" are not sorted. The table has a wrong structure. The current output of the table looks like:
|ean | name | data
--------------------------------------------
|802.0165.813| thefirst | A
|B | thesecond | 802.6725.277
|C | thethird | 570.6761.483
|D | thefourth | 570.6764.519
The first column must be the ean, second the name and third the data. Only the first row is correct. I think its luck.
Its possible to sort the objects in the Array ("inventar") before iterating over it, to get the right structure?
I read somewhere that it is not possible to sort directly in mongoose.
thanks in advance
It appears you are asking about the property order in the object. In ES5 and earlier, properties have NO deterministic order by specification. There are some implementations that will maintain the order the properties were created in, but that was not guaranteed.
In ES6, the spec has been changed to say that properties will remain in the order they are created. But, there is no mechanism for reordering properties on an existing object. If you want to change the order, the work-around would be to create a new object, copy the properties over in the desired order and then replace the original object with the new one.
All that said, normal coding should not care what order the properties are in. You refer to a property on an object as in x.inventar[0].data and it should not matter whether data is the first or last property when you dump the object contents.
Given what you are showing in your sample table, it appears that some piece of code is grabbing the first property and putting it in the first column. That is the wrong way to build the table. Instead, it should grab a specific property name and then the order of the properties on the object simply will not matter. So, I think what you need to do is to fix your jade definition to refer to specific property names, not to just take them in order.
I don't know Jade very well myself, but I think you can do something like this:
table(border='1', cellspacing='3', cellpadding='4')
tr
th(align='center') ean
th(align='center') name
th(align='center') data
each obj in inventar
tr
//edited syntax
td= obj.ean
td= obj.name
td= obj.data

Categories