Display json data in spreadsheet like looking html table using angular - javascript

I need help regarding rendering this JSON data in html table using angular:
[{
"task": "Test1",
"number": 20,
"name": "John"
},
{
"task": "Test1",
"number": 10,
"name": "Doug"
},
{
"task": "Test2",
"number": 50,
"name": "John"
},
{
"task": "Test2",
"number": 100,
"name": "Doug"
}]
My rendered html table should look like this
Test1 Test2
John 20 50
Doug 10 100
Somehow values need to be grouped by, and then rendered, but to keep matching data. Also that first position in array[0][0] should be empty. Any help will be appreciated.

So you can group your data by name , and have Object of arrays like following :
{
"John": [
{
"task": "Test1",
"number": 20,
"name": "John"
},
{
"task": "Test2",
"number": 50,
"name": "John"
}
],
"Doug": [
{
"task": "Test1",
"number": 10,
"name": "Doug"
},
{
"task": "Test2",
"number": 100,
"name": "Doug"
}
]
}
Then , define a function to retrieve data by name & task : getItemBy=function(name,task)
Those two steps will make your algo easy to render HTML table as u want :
DEMO :
var data=[{
"task": "Test1",
"number": 20,
"name": "John"
},
{
"task": "Test1",
"number": 10,
"name": "Doug"
},
{
"task": "Test2",
"number": 50,
"name": "John"
},
{
"task": "Test2",
"number": 100,
"name": "Doug"
}];
var groupBy=function(arr,key) {
return arr.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
//------
var groupedByName=groupBy(data,'name');
var getItemBy=function(name,task){
return groupedByName[name].filter((item)=>item.task===task)
};
//------
//--
console.log(`***** Item where name=John & task=Test1`,
getItemBy('John','Test1')
)
console.log(`****** All data after grouping`,
groupedByName
)

Related

How can I .filter an object by elements within an array inside an object?

I've been playing around trying to learn in an API project using Postman and conducting tests using JavaScript. So far, I have succeeded with the help of reading on websites and watching YouTube videos. Of course, previous tests and playing around have been fairly easy but now I came to a stop. I really tried to figure this out for several weeks but I need further guidance, a push in the right direction or direct help.
What I'm trying to do is to filter out some of the response to only view objects that contain specific data.
To do that, I'm using a filter where I want all products containing a specific value inside an array "product_option_values".
My first approach was to see if I could sort products having any values from the first array, and it worked. It filters just fine.
var filterSmall = jsonData.products.filter(fs => fs.associations.product_option_values);
My next approach was to get to my goal of filtering out products according to specific values inside this array. I tried many simple .(dot) combinations and pointing to [index] to access it without any luck. (I must add that I know how to access this from a specific product, but that way doesn't work when filtering).
I've also tried other approaches such as:
var filterSmall = jsonData.products.filter(fs => fs.associations["product_option_values", 0, "name"] === "S");
and other similar combinations.
This is a very shortened sample of the structure of "products" which in its full form consists of 20 products and far more values inside of it:
{
"products": [
{
"id": 16,
"manufacturer_name": "Graphic Corner",
"quantity": "0",
"price": "12.900000",
"indexed": "1",
"name": "Mountain fox notebook",
"associations": {
"categories": [
{
"id": "2"
},
{
"id": "6"
}
],
"product_option_values": [
{
"id": "22"
},
{
"id": "23"
}
]
}
},
{
"id": 17,
"manufacturer_name": "Graphic Corner",
"quantity": "0",
"price": "12.900000",
"indexed": "1",
"name": "Brown bear notebook",
"associations": {
"categories": [
{
"id": "2"
},
{
"id": "6"
}
],
"product_option_values": [
{
"id": "23"
},
{
"id": "24"
}
]
}
}
]
}
and here is a small and expanded sample from product_option_values:
{
"product_option_values": [
{
"id": 1,
"id_attribute_group": "1",
"color": "",
"position": "0",
"name": "S"
},
{
"id": 2,
"id_attribute_group": "1",
"color": "",
"position": "1",
"name": "M"
},
{
"id": 3,
"id_attribute_group": "1",
"color": "",
"position": "2",
"name": "L"
}
]
}
How do I proceed? Did I do anything correct or even close to it?
Perhaps I've been staring at this for too long.
Thanks in advance.
If you want to compare nested attributes you have to transform the objects (e.g. by using a map operation), so that the relevant attributes are easily accessible for a comparison. If you want to filter by product_option_value id, you could do something like this:
const jsonData = {
"products": [
{
"id": 16,
"manufacturer_name": "Graphic Corner",
"quantity": "0",
"price": "12.900000",
"indexed": "1",
"name": "Mountain fox notebook",
"associations": {
"categories": [
{
"id": "2"
},
{
"id": "6"
}
],
"product_option_values": [
{
"id": "22"
},
{
"id": "23"
}
]
}
},
{
"id": 17,
"manufacturer_name": "Graphic Corner",
"quantity": "0",
"price": "12.900000",
"indexed": "1",
"name": "Brown bear notebook",
"associations": {
"categories": [
{
"id": "2"
},
{
"id": "6"
}
],
"product_option_values": [
{
"id": "23"
},
{
"id": "24"
}
]
}
}
]
};
const sample = {
"product_option_values": [
{
"id": 22,
"id_attribute_group": "1",
"color": "",
"position": "0",
"name": "S"
},
{
"id": 2,
"id_attribute_group": "1",
"color": "",
"position": "1",
"name": "M"
},
{
"id": 3,
"id_attribute_group": "1",
"color": "",
"position": "2",
"name": "L"
}
]
};
const ids = sample.product_option_values.map((el) => String(el.id));
console.log(ids);
const filtered = jsonData.products.filter((fs) => fs.associations.product_option_values.map((e) => e.id).some((f) => ids.includes(f)));
console.log(filtered);

Knexnest query not returning data in array even though this is what is expected

I have this knexnest query:
const query = knex.select([
'notes.id AS _id',
'notes.note AS _note',
'notes.timestamp AS _timestamp',
'customers.id AS _customerId',
'users.name AS _name',
'products.id AS _productId',
'tags.id AS _tags_tagId',
'tags.title AS _tags_tagTitle',
'tags.type AS _tags_tagType',
]).from('notes')
.join('users', 'notes.user_id', 'users.id')
.join('customers', 'notes.customer_id', 'customers.id')
.leftJoin('products', 'notes.product_id', 'products.id')
.leftJoin('note_tags', 'notes.id', 'note_tags.note_id')
.leftJoin('tags', 'note_tags.tag_id', 'tags.id')
.where('customers.id', customerId);
return knexnest(query);
My response json looks like this:
{
"id": 47,
"note": "This is an updated1 note",
"timestamp": "2019-07-12T15:17:27.281Z",
"customerId": 111781,
"name": "Paul",
"productId": 1,
"tags": {
"tagId": 4,
"tagTitle": "price",
"tagType": "product"
}
}
The problem is that the database returns more than one tag, only one is displayed. I'm expecting a response like this:
{
"id": 47,
"note": "This is an updated1 note",
"timestamp": "2019-07-12T15:17:27.281Z",
"customerId": 111781,
"name": "Paul",
"productId": 1,
"tags": {[
{
"tagId": 4,
"tagTitle": "price",
"tagType": "product"
},
{
"tagId": 5,
"tagTitle": "quality",
"tagType": "product"
}
]}
}
Have I got something wrong in my query that is causing this?
Got it. I was missing double __ in the tags:
'tags.id AS _tags__tagId',
'tags.title AS _tags__tagTitle',
'tags.type AS _tags__tagType'

Convert JSON object

I need to convert JSON object into different format.
My JSON looks like this -
{
"approver": [
{
"roleId": "New Approver",
"level": "1",
"firstName": "Alan"
},
{
"roleId": "New Approver",
"level": "2",
"firstName": "Alex"
},
{
"roleId": "New Approver",
"level": "1",
"firstName": "Mike"
},
{
"roleId": "USFA",
"level": "1",
"firstName": "Matt"
},
{
"roleId": "USFA",
"level": "1",
"firstName": "John"
}
]
}
Expected output:
Output = [
{ roleName : "New Approver",
levels : [
{ level : "1",
users : ["alan", "mike"] },
{ level : "2",
users : ["alex"] }
] },
{ roleName : "USFA",
levels : [
{ level : "1",
users : ["matt", "john"]
}]
}]
I have tried using reduce function but it does not give me expected results. Could anyone help me convert the object?
Thanks
How about try like Array.from(JSON_object_here)

Returning a new JSON object with filtered results

I'm looking to return a new JS object from an existing JS object, after filtering for some result.
Say I have the following JS object:
{ "Examples" :
[ { "id": 1, "name": "Tim", "answer": "yes"},
{ "id": 2, "name": "Jon", "answer": "no"},
{ "id": 3, "name": "Don", "answer": "yes" ] }
I want to filter through this object for all yes answers and return an object that looks like this:
{ "Examples" :
[ { "id" : 1, "name": "Tim", "answer": "yes"},
{ "id" : 3, "name": "Don", "answer": "yes"} ] }
First: that's a JavaScript object, not a JSON object. JSON is a serialization scheme.
You can filter the array with .filter():
var obj = { "Examples" :
[ { "id": 1, "name": "Tim", "answer": "yes"},
{ "id": 2, "name": "Jon", "answer": "no"},
{ "id": 3, "name": "Don", "answer": "yes" ] };
obj.Examples = obj.Examples.filter(function(entry) {
return entry.answer === "yes";
});

Adding object properties from one JSON data file to another

I have two local JSON files. I want to add the property of one object from one file to the corresponding object in the other file.
Here is an example..
Array1:
[
{
"id": 1,
"username": "Joe Smith",
"pic": "images/profile/Joe_smith.jpg"
},
{
"id": 2,
"username": "Jane Smith",
"pic": "images/profile/Jane_smith.jpg"
}
]
Array2:
[
{
"id": 3,
"userId": 1,
"profession": "dentist"
},
{
"id": 4,
"userId": 2,
"profession": "pilot"
}
The idea is to add the "pic" property from Array1 to the correct object in Array2. If the id from Array1 matches the userId from Array2, it's a correct match. Array2 would end up looking like this:
[
{
"id": 3,
"userId": 1,
"profession": "dentist",
"pic": "images/profile/Joe_smith.jpg"
},
{
"id": 4,
"userId": 2,
"profession": "pilot",
"pic": "images/profile/Jane_smith.jpg"
}
Afterwards I'm going to use angular to display a name with the face. Hope I explained that ok. Any help would be much appreciated!
Just for the fun of it. In this example using https://lodash.com.
var people = [
{ "id": 1, "username": "Joe Smith", "pic": "images/profile/Joe_smith.jpg" },
{ "id": 2, "username": "Jane Smith", "pic": "images/profile/Jane_smith.jpg"},
{ "id": 3, "username": "I play too much games", "pic": "images/profile/toomuch.jpg"}
];
var professions = [
{ "id": 3, "userId": 1, "profession": "dentist" },
{ "id": 4, "userId": 2, "profession": "pilot" }
];
var workers = _.map(people, function(human) {
var work = _.findWhere(professions, { 'userId': human.id });
return _.extend(human, work ? work : { 'profession' : 'unemployed' });
});
console.log(workers);

Categories

Resources