I have an array that looks like this:
var roles = [
{ "label": "Super Auditor", "value": 4 },
{ "label": "Super Finance Officer", "value": 3 },
{ "label": "Super Manager", "value": 2 },
{ "label": "Super Admin", "value": 1 }
]
I need to find if it is in array and get that object.
var needToFind = [4, 1]
Expected Results:
var results =[
{ "label": "Super Auditor", "value": 4 },
{ "label": "Super Admin", "value": 1 }
]
I just don't know how to do it. TY
You can use _.intersectionWith():
var roles = [
{ "label": "Super Auditor", "value": 4 },
{ "label": "Super Finance Officer", "value": 3 },
{ "label": "Super Manager", "value": 2 },
{ "label": "Super Admin", "value": 1 }
]
var needToFind = [4, 1]
var result = _.intersectionWith(roles, needToFind, (a, b) => a.value === b)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Here's an answer using VanillaJS
const roles = [
{ "label": "Super Auditor", "value": 4 },
{ "label": "Super Finance Officer", "value": 3 },
{ "label": "Super Manager", "value": 2 },
{ "label": "Super Admin", "value": 1 }
];
const needToFind = [4, 1];
const results = roles.filter(obj => needToFind.includes(obj.value))
console.log(results)
Basically you apply filter on roles and using includes to see if value exist in needtoFind
Related
Input 01:
{
"labelItems": [{
"label": "manager",
"role": "MA"
}, {
"label": "Developer",
"role": "DEV"
}]
}
Input 02:
{
"List": [{
"id": "M123",
"label": "Manager"
},
{
"id": "L240",
"label": "Lead"
},
{
"id": "D250",
"label": "Developer"
}
]
}
Final output:
{
"Labels": [{
"id": "M123",
"role": "MA"
},
{
"id": "D250",
"role": "DEV"
}
]
}
Can anyone provide me the above desired final output response, we have two input payloads and compare two payloads with the label field and get the id & role fields from the array of the list.
Thanks in Advance,
One way would be to iterate on Input 02 ( I have set Input 01 as the payload to this script) and pass over the label to filter the payload, to procure the corresponding role. Have used capitalize since the manager in payload (Input 01) starts with lowercase m while the same starts with Uppercase m in Input 02 label for id M123.
%dw 2.0
output application/json
import * from dw::core::Strings
var inp2 = {
"List": [{
"id": "M123",
"label": "Manager"
},
{
"id": "L240",
"label": "Lead"
},
{
"id": "D250",
"label": "Developer"
}
]
}
---
Labels: inp2.List map ((item, index) -> {
id: item.id,
role: (payload.labelItems filter (capitalize($.label) == item.label )).'role'[0]
}) filter (!($.role == null))
Another modification to this could be:
%dw 2.0
output application/json
import * from dw::core::Strings
var inp2 = {
"List": [{
"id": "M123",
"label": "Manager"
},
{
"id": "L240",
"label": "Lead"
},
{
"id": "D250",
"label": "Developer"
}
]
}
var interim = payload.labelItems map {
(capitalize($.label)): $.role
}
---
Labels: inp2.List map ((item, index) -> {
id: item.id,
role: interim[(item.label)][0]
}) filter (!($.role == null))
Another way to do this is by using joins. I have used leftJoin for joining the arrays.
%dw 2.0
import * from dw::core::Arrays
output application/json
var inp2 = {
"List": [{
"id": "M123",
"label": "Manager"
},
{
"id": "L240",
"label": "Lead"
},
{
"id": "D250",
"label": "Developer"
}
]
}
---
Labels: leftJoin (payload.labelItems, inp2.List,
(labelItems)-> lower(labelItems.label), (listItems) -> lower(listItems.label))
map {
id: $.r.id,
role: $.l.role
}
You can iterate over input 1 and compare the current item's label with label in in2's list to get the corresponding id
%dw 2.0
output application/json
var in1={
"labelItems": [{
"label": "manager",
"role": "MA"
}, {
"label": "Developer",
"role": "DEV"
}]
}
var in2={
"List": [{
"id": "M123",
"label": "Manager"
},
{
"id": "L240",
"label": "Lead"
},
{
"id": "D250",
"label": "Developer"
}
]
}
---
Labels: in1.labelItems default [] map (item, index) -> {
id: in2.List[?(lower($.label) == lower(item.label))][0].id,
role: item.role
}
Have used lower to avoid any case sensitivity
I am trying to convert JSON into an SQL table. The source is the response from a REST API. I do not have the opportunity to change the response.
The response contains data on several projects. Projects are returned as individual members of a global projects object.
As the projectid is not at the same level with the other data and also does not have a name
SELECT * FROM OPENJSON (#JSON);
fails to parse it properly. I end up with one row for projects and the json object as the value. Also without the proper way to refer to the elements I could not figure out a way to use JSON_VALUE.
Below is a sample structure. Actual data has much more properties and variations between the projects. I prefer to solve this in SQL. But any way to sort out the JSON will be appreciated. This is my first exposure to JSON. I want to ask if I am missing something very obvious...
TIA
{
"projects": {
"project1id": {
"data": {
"customer": "Cust1",
"name": "Project Name 1"
},
"projectType": "type0"
},
"project2id": {
"data": {
"customer": "Customer 2",
"name": "Name 2",
"projectManager": "Man Ager"
},
"projectType": "type2"
},
"Project3id": {
"data": {
"customer": "Another Customer",
"name": "Another Project"
},
"projectType": "type1"
}
}
}
Expected Result
ProjectId
Project Name
Customer
Project Type
Project Manager
project1id
Project Name 1
Cust 1
type0
project2id
Customer 2
type2
Man Ager
project3id
Another Project
Another Customer
type1
Excerpt from original Json:
{
"projects": {
"10000eumbvqn76": {
"data": {
"inquiryNumber": "34635",
"customer": "C AS",
"name": "E W ",
"orderNumber": "1000",
"seller": "M A",
"projectManager": "B O V",
"phase": "fulfillment",
"exchange": {
"deadline": {
"time": [
24,
0
],
"timezone": [
1,
0
]
},
"settings": {
"client": {
"codes": [
{
"id": "1",
"label": "Code 1"
},
{
"id": "4",
"label": "Code 4"
},
{
"id": "5",
"label": "Code 5"
},
{
"id": "2",
"label": "Code 2"
},
{
"id": "3",
"label": "Code 3"
}
],
"approvedCodes": [
"1"
],
"cycles": {
"producer": 21,
"consumer": 21
}
},
"clientForInformation": {
"cycles": {
"producer": 21
}
},
"supplier": {
"codes": [
{
"id": "1",
"label": "Code 1"
},
{
"id": "4",
"label": "Code 4"
},
{
"id": "5",
"label": "Code 5"
},
{
"id": "2",
"label": "Code 2"
},
{
"id": "3",
"label": "Code 3"
}
],
"approvedCodes": [
"1"
],
"cycles": {
"producer": 14,
"consumer": 14
}
},
"supplierIsProducer": {
"supplierRole": "producer"
},
"supplierIsConsumer": {
"supplierRole": "consumer"
}
},
"sequences": {
"$salesPurchase": {
"label": "Client RFQ to OC",
"settings": "supplierIsProducer",
"group": "inquiry"
},
"$salesPurchaseSupplier": {
"label": "Supplier RFQ to OC",
"settings": "supplierIsConsumer",
"group": "inquiry"
},
"$salesClient": null,
"$salesClientFrom": null,
"$client": {
"label": "To client",
"group": "order-fulfillment",
"order": [
"IFR",
"IFI"
],
"stages": {
"IFR": {
"label": "Issued for Review",
"phase": "forApproval",
"settings": "client"
},
"IFI": {
"label": "Issued for Information",
"phase": "forInformation",
"settings": "clientForInformation"
}
},
"interpret": {
"type": "unordered"
}
},
"$supplier": {
"label": "From supplier",
"group": "order-fulfillment-supplier",
"settings": "supplier"
},
"$supplierTo": {
"label": "To supplier",
"group": "order-fulfillment-supplier",
"settings": "supplierIsConsumer"
},
"$internal": null
}
},
"officialMailIdFormat": "M-1000-0001",
"transmittalMailIdFormat": "TR-1000-0001",
"commercialMailIdFormat": "Bid-34635-0001",
"officialMailIdFormats": [
{
"label": "Official",
"format": "M-1000-0001"
},
{
"label": "Commercial",
"format": "Bid-34635-0001"
}
]
},
"projectType": "commercial"
},
"1000hf30ua": {
"data": {
"inquiryNumber": "100",
"customer": "S M I Y P L",
"name": "1000 FSPO ",
"seller": "L H",
"projectManager": "L H",
"phase": "inquiry",
"exchange": {
"deadline": {
"time": [
24,
0
],
"timezone": [
1,
0
]
},
"settings": {
"client": {
"codes": [
{
"id": "1",
"label": "Code 1"
},
{
"id": "4",
"label": "Code 4"
},
{
"id": "5",
"label": "Code 5"
},
{
"id": "2",
"label": "Code 2"
},
{
"id": "3",
"label": "Code 3"
}
],
"approvedCodes": [
"1"
],
"cycles": {
"producer": 21,
"consumer": 21
}
},
"clientForInformation": {
"cycles": {
"producer": 21
}
},
"supplier": {
"codes": [
{
"id": "1",
"label": "Code 1"
},
{
"id": "4",
"label": "Code 4"
},
{
"id": "5",
"label": "Code 5"
},
{
"id": "2",
"label": "Code 2"
},
{
"id": "3",
"label": "Code 3"
}
],
"approvedCodes": [
"1"
],
"cycles": {
"producer": 14,
"consumer": 14
}
},
"supplierIsProducer": {
"supplierRole": "producer"
},
"supplierIsConsumer": {
"supplierRole": "consumer"
}
},
"sequences": {
"$salesPurchase": {
"label": "Client RFQ to OC",
"settings": "supplierIsProducer",
"group": "inquiry"
},
"$salesPurchaseSupplier": {
"label": "Supplier RFQ to OC",
"settings": "supplierIsConsumer",
"group": "inquiry"
},
"$salesClient": null,
"$salesClientFrom": null,
"$client": {
"label": "To client",
"group": "order-fulfillment",
"order": [
"IFR",
"IFI"
],
"stages": {
"IFR": {
"label": "Issued for Review",
"phase": "forApproval",
"settings": "client"
},
"IFI": {
"label": "Issued for Information",
"phase": "forInformation",
"settings": "clientForInformation"
}
},
"interpret": {
"type": "unordered"
}
},
"$supplier": {
"label": "From supplier",
"group": "order-fulfillment-supplier",
"settings": "supplier"
},
"$supplierTo": {
"label": "To supplier",
"group": "order-fulfillment-supplier",
"settings": "supplierIsConsumer"
},
"$internal": null
}
},
"officialMailIdFormat": "M-100-0001",
"transmittalMailIdFormat": "TR-100-0001",
"commercialMailIdFormat": "Bid-100-0001",
"officialMailIdFormats": [
{
"label": "Official",
"format": "M-100-0001"
},
{
"label": "Commercial",
"format": "Bid-100-0001"
}
],
"orderNumber": "100"
},
"projectType": "commercial"
}
}
}
Possible options are: 1) Using OPENJSON() twice (with default and explicit schema) and an additional APPLY operator or 2) Using OPENJSON() (with default schema) and JSON_VALUE():
JSON:
DECLARE #json nvarchar(max) = N'{
"projects":{
"project1id":{
"data":{
"customer":"Cust1",
"name":"Project Name 1"
},
"projectType":"type0"
},
"project2id":{
"data":{
"customer":"Customer 2",
"name":"Name 2",
"projectManager":"Man Ager"
},
"projectType":"type2"
},
"Project3id":{
"data":{
"customer":"Another Customer",
"name":"Another Project"
},
"projectType":"type1"
}
}
}'
Statement with OPENJSON() and APPLY operator:
SELECT j1.[key] AS projectId, j2.*
FROM OPENJSON(#json, '$.projects') j1
CROSS APPLY OPENJSON(j1.[value], '$') WITH (
name nvarchar(100) '$.data.name',
customer nvarchar(100) '$.data.customer',
projectType nvarchar(100) '$.projectType',
projectManager nvarchar(100) '$.data.projectManager'
) j2
Statement with OPENJSON() and JSON_VALUE():
SELECT
projectId = [key],
name = JSON_VALUE([value], '$.data.name'),
customer = JSON_VALUE([value], '$.data.customer'),
projectType = JSON_VALUE([value], '$.projectType'),
projectManager = JSON_VALUE([value], '$.data.projectManager')
FROM OPENJSON(#json, '$.projects')
I am trying to get data from my database but when I show and make it become api response, I have some problem for grouping it based on productid.
I have response data that created based on golang like this:
[
{
"product_id": "1",
"product_name": "Cardigan",
"pitems": [
{
"id": "625ad1bc-66c5-440e-a527-d029d401ec2b",
"name": "Box",
"qty": 1
},
{
"id": "625ad1bc-66c6-440e-a527-d029d401ec2b",
"name": "test items1",
"qty": 1
},
{
"id": "625ad1bc-66c7-440e-a527-d029d401ec2b",
"name": "test items2",
"qty": 1
},
{
"id": "625ad1bc-66c8-440e-a527-d029d401ec2b",
"name": "test items3",
"qty": 1
}
]
},
{
"product_id": "2",
"product_name": "Polo",
"product_sku": "P01",
"items": [
{
"id": "625ad1bc-66c5-440e-a527-d029d401ec2b",
"name": "Box",
"qty": 1
},
{
"id": "625ad1bc-66c6-440e-a527-d029d401ec2b",
"name": "test items1",
"qty": 1
},
{
"id": "625ad1bc-66c7-440e-a527-d029d401ec2b",
"name": "test items2",
"qty": 1
},
{
"id": "625ad1bc-66c8-440e-a527-d029d401ec2b",
"name": "test items3",
"qty": 1
}
]
}
]
But This response is not my expected result, my expected result is like:
[
{
"product_id": "1",
"product_name": "Cardigan",
"pitems": [
{
"id": "625ad1bc-66c5-440e-a527-d029d401ec2b",
"name": "Box",
"qty": 1
},
{
"id": "625ad1bc-66c6-440e-a527-d029d401ec2b",
"name": "test items1",
"qty": 1
},
{
"id": "625ad1bc-66c7-440e-a527-d029d401ec2b",
"name": "test items2",
"qty": 1
}
]
},
{
"product_id": "2",
"product_name": "Polo",
"product_sku": "P01",
"items": [
{
"id": "625ad1bc-66c8-440e-a527-d029d401ec2b",
"name": "test items3",
"qty": 1
}
]
}
]
Can Anyone help me to solve my problem?
What does it mean to show detailed data?
the easy way is:
create 2 func like this:
func detail(id int)(result model.Struct)
{ return result }
func product()(result model.Struct_Result) {
for data.Next() {
// call func detail
data.Scan(&id, &product)
detailResult := detail(id)
// then put together with struct and mix append ()
outputLoop := model.Result{
"product_id": id,
"pitems": [
{
"id": detailResult.id,
"name": detailResult.name,
"qty": detailResult.qty
},
]
}
result = append(result,outputLoop)
}
return result
}
Let's say I have users, skills and user_skill tables.
How can I query so that if I have 3 users, I get 3 objects (in an array, obviously) and for each user's object there should be a nested array with all the skills?
Something like this:
{
"users": [
{
"name": "dusan",
"id": 1,
"facebook": "dusan's facebook",
"skills": [
{"name": "skill1", "id": 1}
{"name": "skill2", "id": 2}
]
},
{
"name": "jenny",
"id": 2,
"facebook": "jenny's facebook",
"skills": [
{"name": "skill1", "id": 1}
{"name": "skill2", "id": 2}
]
},
{
"name": "michael",
"id": 3,
"facebook": "michael's facebook",
"skills": [
{"name": "skill1", "id": 1}
{"name": "skill2", "id": 2}
]
},
]
}
My code:
await db("users")
.join("user_skill", "users.id", "skills.user_id")
.join("skills", "skills.id", "user_skill.id")
.select(
"users.name as name",
"users.id as id",
"skills.name as skill",
"skills.id as skill_id"
);
The above code returns a completely flat structured JSON, and I want to have skills nested inside the user object.
{
"users": [
{
"name": "dusan",
"id": 1,
"skill": "node.js",
"skill_id": 1
},
{
"name": "dusan",
"id": 1,
"skill": "php",
"skill_id": 2
},
{
"name": "dusan",
"id": 1,
"skill": "mongodb",
"skill_id": 3
},
{
"name": "jaca",
"id": 2,
"skill": "angular",
"skill_id": 4
},
{
"name": "jaca",
"id": 2,
"skill": "reactjs",
"skill_id": 5
},
]
}
I understand this is how SQL is designed, to return flat structure, but is there a way I could accomplish the nesting of related data?
A fellow developer has come up with this solution, so I've decided to share it in hope that someone would find it helpful:
returnedUsers = {
"users": [{
"name": "dusan",
"id": 1,
"skill": "node.js",
"skill_id": 1
},
{
"name": "dusan",
"id": 1,
"skill": "php",
"skill_id": 2
},
{
"name": "dusan",
"id": 1,
"skill": "mongodb",
"skill_id": 3
},
{
"name": "jaca",
"id": 2,
"skill": "angular",
"skill_id": 4
},
{
"name": "jaca",
"id": 2,
"skill": "reactjs",
"skill_id": 5
},
]
};
const groupBy = (array, key) =>
array.reduce((a, c) => ({
...a,
[c[key]]: [...a[c[key]] || [], c]
}), {});
const uniques = (...values) =>
Array.from(new Set([].concat(...values).filter(Boolean)));
const singularize = array =>
array.length == 1 ? array[0] : array;
const singularizedUniques = (...values) =>
singularize(uniques(...values));
const mergeCollect = array =>
array.reduce((mergedObject, curentObject) =>
Object.entries(curentObject).reduce((newObject, [k, v]) => ({
...newObject,
[k]: singularizedUniques(newObject[k], v)
}), mergedObject), {});
const groupByKey = (array, key) =>
Object.fromEntries(Object.entries(groupBy(array, key)).map(([k, v]) => [k, mergeCollect(v)]));
console.log(groupByKey(returnedUsers.users, 'id'));
Hi I have the following object:
{ "name": "Joe", "email": "joe.smith#test.com", "items": [ { "id": "1", "name": "Name 1" }, { "id": "2", "name": "Name 2" }...] }
I need to remove the name property from all the 'items', I have tried using omit but can't seem to get this working:
_.omit(this.user, ["items.name"]);
Any help would be great!
The _.omit() method doesn't work on multiple items in this way. You can use _.map() with _.omit():
const user = { "name": "Joe", "email": "joe.smith#test.com", "items": [ { "id": "1", "name": "Name 1" }, { "id": "2", "name": "Name 2" }] }
const result = {
...user,
items: _.map(user.items, user => _.omit(user, 'name'))
}
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>