I'm learning Javascript and getting started with React. I'm attempting to build a Materials-UI's DataGrid and need to structure my data accordingly. I have the following piece of code that prepares the Rows and Columns for DataGrid but I feel it may be "slow" and wondering if I can get the community's input on how it can be written more efficiently. Any ideas/solutions would be appreciated. Thanks.
input:
const values = [
{
"documentId": "12345",
"documentDirectory": "Canadian PnC",
"properties": [
{
"name": "HoldingNumber",
"type": "STRING",
"value": "88888",
},
{
"name": "DocumentType",
"type": "STRING",
"value": "TAC",
},
{
"name": "DocumentName",
"type": "STRING",
"value": "Income",
},
]
},
{
"documentId": "54321",
"documentDirectory": "Wealth",
"properties": [
{
"name": "HoldingNumber",
"type": "STRING",
"value": "99999",
},
{
"name": "DocumentType",
"type": "STRING",
"value": "TAC",
},
{
"name": "DocumentName",
"type": "STRING",
"value": "Appraisal",
},
]
}
];
output:
//console.log(cols);
[
{
field: "DocumentDirectory", headerName: "DocumentDirectory", width: 200
},
{
field: "DocumentId", headerName: "DocumentId", width: 200
},
{
field: "HoldingNumber", headerName: "HoldingNumber", width: 200
},
{
field: "DocumentType", headerName: "DocumentType", width: 200
},
{
field: "DocumentName", headerName: "DocumentName", width: 200
}
]
//console.log(rows);
[
{
id: 0,
DocumentDirectory: "Canadian PnC",
DocumentId: "12345",
HoldingNumber: "88888",
DocumentType: "TAC",
DocumentName: "Income"},
{
id: 1,
DocumentDirectory: "Wealth",
DocumentId: "54321",
HoldingNumber: "99999",
DocumentType: "TAC",
DocumentName: "Appraisal"
}
]
I'm currently achieving it the using the following:
const docDirectory = values.map(result => result.documentDirectory);
const docId = values.map(result => result.documentId);
const docProperties = values.map(result => result.properties);
let cols= [];
let rows= [];
for (let i = 0; i < docProperties.length; i++) {
const p = docProperties[i];
let o = {};
o["id"] = i;
o["DocumentDirectory"] = docDirectory[i];
o["DocumentId"] = docId[i];
if (i === 0) {
cols.push({ field: "DocumentDirectory", headerName: "DocumentDirectory", width: 200 });
cols.push({ field: "DocumentId", headerName: "DocumentId", width: 200 });
}
for (let j = 0; j < p.length; j++) {
let nam = p[j].name;
let val = p[j].value;
o[nam.replace(/\s+/, "")] = val;
if (i === 0) {
cols.push({ field: nam.replace(/\s+/, ""), headerName: nam, width: 200 });
}
}
rows.push(o);
}
console.log(cols);
console.log(rows);
const values = [
{
documentId: '12345',
documentDirectory: 'Canadian PnC',
properties: [
{
name: 'HoldingNumber',
type: 'STRING',
value: '88888'
},
{
name: 'DocumentType',
type: 'STRING',
value: 'TAC'
},
{
name: 'DocumentName',
type: 'STRING',
value: 'Income'
}
]
},
{
documentId: '54321',
documentDirectory: 'Wealth',
properties: [
{
name: 'HoldingNumber',
type: 'STRING',
value: '99999'
},
{
name: 'DocumentType',
type: 'STRING',
value: 'TAC'
},
{
name: 'DocumentName',
type: 'STRING',
value: 'Appraisal'
}
]
}
];
const cols = [
{
field: 'DocumentDirectory',
headerName: 'DocumentDirectory',
width: 200
},
{
field: 'DocumentId',
headerName: 'DocumentId',
width: 200
},
...values[0].properties.map(p => ({
field: p.name,
headerName: p.name,
width: 200
}))
];
const rows = values.map((value, index) => {
return {
id: index,
DocumentDirectory: value.documentDirectory,
DocumentId: value.documentId,
...value.properties.reduce(
(val, cur) => ({
...val,
[cur.name]: cur.value
}),
{}
)
};
});
console.log(cols);
console.log(rows);
const values = [{
"documentId": "12345",
"documentDirectory": "Canadian PnC",
"properties": [{
"name": "HoldingNumber",
"type": "STRING",
"value": "88888",
},
{
"name": "DocumentType",
"type": "STRING",
"value": "TAC",
},
{
"name": "DocumentName",
"type": "STRING",
"value": "Income",
},
]
},
{
"documentId": "54321",
"documentDirectory": "Wealth",
"properties": [{
"name": "HoldingNumber",
"type": "STRING",
"value": "99999",
},
{
"name": "DocumentType",
"type": "STRING",
"value": "TAC",
},
{
"name": "DocumentName",
"type": "STRING",
"value": "Appraisal",
},
]
}
];
const allCols = values.reduce((prev, { documentDirectory, properties }) => ([
...prev,
{ field: documentDirectory, headerName: documentDirectory, width: 200 },
...properties.map(({name: field, name: headerName}) => ({field, headerName, width: 200}))
]), [])
const cols = [...new Set(allCols.map(JSON.stringify))].map(JSON.parse)
console.log(cols)
const rows = values.reduce((prev, next) => ([
...prev,
...next.properties.map(property => ({
DocumentDirectory: next.DocumentDirectory,
DocumentId: next.DocumentId,
...property
}))
]), []).map((row, key) => ({id: key, ...row}))
console.log(rows)
Related
We need to update the object in nested objects using recursion in typescript .Need to add extra properties to the object which is in a nested object . Nesting can change overtime and so recursion will only work
Below is the input data :
[
{
"headerName": "Group 1",
"children": [
{
"field": "G1-C1"
},
{
"field": "G1-C2"
}
]
},
{
"headerName": "Group 2",
"children": [
{
"headerName": "G2 - C1",
"children": [
{
"field": "G2 - C1-C1"
},
{
"field": "G2 - C1-C2"
}
]
},
{
"field": "G2-C2"
},
{
"field": "G2-C3"
}
]
},
{
"headerName": "Group3",
"children": [
{
"field": "G3-C1"
},
{
"field": "G3-C2"
}
]
}
]
which needed to be transformed as :
[
{
"headerName": "Group 1",
"children": [
{
"field": "G1-C1",
"visible": true,
"width": 200,
"headerName": "Group1"
},
{
"field": "G1-C2",
"visible": true,
"width": 200,
"headerName": "Group1"
}
]
},
{
"headerName": "Group 2",
"children": [
{
"headerName": "G2 - C1",
"children": [
{
"field": "G2 - C1-C1",
"width": 200,
"headerName": "Group2-C1"
},
{
"field": "G2 - C1-C2",
"width": 200,
"headerName": "Group2-C1"
}
]
},
{
"field": "G2-C2",
"width": 200,
"headerName": "Group2"
},
{
"field": "G2-C3",
"width": 200,
"headerName": "Group2"
}
]
},
{
"headerName": "Group3",
"children": [
{
"field": "G3-C1",
"width": 200,
"headerName": "Group3"
},
{
"field": "G3-C2",
"width": 200,
"headerName": "Group3"
}
]
}
]
Tried several ways but was not able to find a way . It would be great help of there is any quick way to find a solution for this problem . This below method works but not sure if its is correct .
formatData(columns: any) {
columns.forEach((i: any,index) => {
if (i.hasOwnProperty('children')) {
this.formatData(i.children);
} else {
columns[index] = {...{ field : i.field, headerName:
i.field, sortable: true, hide: false }};
}
});
}
FIrst of all we need to define type of our data structure:
type WithChildren = {
headerName: string,
children: DataStructure[]
}
type WithoutChildrenInput = {
field: string,
}
type WithoutChildrenOutput = {
field: string,
} & Pick<WithChildren, 'headerName'>
type DataStructure = WithChildren | WithoutChildrenInput
type DataStructureOutput = WithChildren | WithoutChildrenOutput
Then we can define our logic:
const fieldOutput = (
field: string,
headerName: string
) => ({
field,
headerName,
visible: true,
width: 200,
})
const childrenOutput = (headerName: string, children: DataStructure[]) => (
{ headerName, children: builder(children, headerName) }
)
const withChildren = <Obj, Prop extends string>(obj: DataStructure)
: obj is WithChildren =>
Object.prototype.hasOwnProperty.call(obj, 'children');
const builder = (data: DataStructure[], headerName = ''): DataStructureOutput[] =>
data.reduce<DataStructureOutput[]>((acc, elem) =>
withChildren(elem)
? [...acc, childrenOutput(elem.headerName, elem.children)]
: [...acc, fieldOutput(elem.field, headerName)], [])
const result = builder(data)
I have created two helpers: childrenOutput and fieldOutput.
fieldOutput - just creates a plain object of field entity. nothing special
childrenOutput - generates expected data structure with children and calls under the hood builder function.
withChildren - is a user defined typeguard which helps narrow the type
You may think that it is a bad practice to call function before you define it. You can declare builder with function keyword or pass third argument to childrenOutput like here:
const childrenOutput = (headerName: string, children: DataStructure[], callback: (data: DataStructure[], headerName: string) => DataStructureOutput[]) => (
{ headerName, children: builder(children, headerName) }
)
It is up to you.
Whole code:
type WithChildren = {
headerName: string,
children: DataStructure[]
}
type WithoutChildrenInput = {
field: string,
}
type WithoutChildrenOutput = {
field: string,
} & Pick<WithChildren, 'headerName'>
type DataStructure = WithChildren | WithoutChildrenInput
type DataStructureOutput = WithChildren | WithoutChildrenOutput
const data: DataStructure[] = [
{
"headerName": "Group 1",
"children": [
{
"field": "G1-C1"
},
{
"field": "G1-C2"
}
]
},
{
"headerName": "Group 2",
"children": [
{
"headerName": "G2 - C1",
"children": [
{
"field": "G2 - C1-C1"
},
{
"field": "G2 - C1-C2"
}
]
},
{
"field": "G2-C2"
},
{
"field": "G2-C3"
}
]
},
{
"headerName": "Group3",
"children": [
{
"field": "G3-C1"
},
{
"field": "G3-C2"
}
]
}
]
const fieldOutput = (
field: string,
headerName: string
) => ({
field,
headerName,
visible: true,
width: 200,
})
const childrenOutput = (headerName: string, children: DataStructure[], callback: (data: DataStructure[], headerName: string) => DataStructureOutput[]) => (
{ headerName, children: builder(children, headerName) }
)
const withChildren = <Obj, Prop extends string>(obj: DataStructure)
: obj is WithChildren =>
Object.prototype.hasOwnProperty.call(obj, 'children');
const builder = (data: DataStructure[], headerName = ''): DataStructureOutput[] =>
data.reduce<DataStructureOutput[]>((acc, elem) =>
withChildren(elem)
? [...acc, childrenOutput(elem.headerName, elem.children, builder)]
: [...acc, fieldOutput(elem.field, headerName)], [])
const result = builder(data)
console.log({ result })
Playground
I'm trying to group an array of objects. The array should be grouped following this quote:
Group by type respecting the sequence.
Array I wish to group
var arrayObj = [
{ "type": "user", "text": "user1" },
{ "type": "user", "text": "user2" },
{ "type": "user", "text": "user3" },
{ "type": "clerk", "text": "clerk1" },
{ "type": "user", "text": "user4" },
{ "type": "clerk", "text": "clerk2" },
{ "type": "clerk", "text": "clerk3" },
{ "type": "user", "text": "user5" },
{ "type": "user", "text": "user6" }
];
The way I want it to be grouped:
var newArray = [
[
{type: "user", text: "user1"},
{type: "user", text: "user2"},
{type: "user", text: "user3"}
],
[
{type: "clerk", text: "clerk1"}
],
[
{type: "user", text: "user4"}
],
[
{type: "clerk", text: "clerk2"},
{type: "clerk", text: "clerk3"}
],
[
{type: "user", text: "user5"},
{type: "user", text: "user6"}
]
];
What i tried:
I'm trying to use a filter, but without success since it even groups, but it groups all that are of the same type without respecting the sequence I want (from the array above);
var arrayObj = [
{ "type": "user", "text": "user1" },
{ "type": "user", "text": "user2" },
{ "type": "user", "text": "user3" },
{ "type": "clerk", "text": "clerk1" },
{ "type": "user", "text": "user4" },
{ "type": "clerk", "text": "clerk2" },
{ "type": "clerk", "text": "clerk3" },
{ "type": "user", "text": "user5" },
{ "type": "user", "text": "user6" }
];
var newArray = [];
newArray.push(filtrarArray(arrayObj, 'clerk'));
newArray.push(filtrarArray(arrayObj, 'user'));
console.log(newArray);
function filtrarArray(array, type) {
return array.filter(function (val) {
return val.type === type;
});
}
The snippet below first sorts the array by type, which then makes it easy to loop through and group. Let me know if this solves your problem :)
EDIT
Just realized you didn't need sorting, so I commented the sort function out, but it's always there to be uncommented if you change your mind :)
const arrayObj = [
{ type: 'user', text: 'user1' },
{ type: 'user', text: 'user2' },
{ type: 'user', text: 'user3' },
{ type: 'clerk', text: 'clerk1' },
{ type: 'user', text: 'user4' },
{ type: 'clerk', text: 'clerk2' },
{ type: 'clerk', text: 'clerk3' },
{ type: 'user', text: 'user5' },
{ type: 'user', text: 'user6' },
];
const group = ar =>
ar
// .sort((a, b) => (a.type < b.type ? -1 : 1))
.reduce((newAr, obj, i) => {
if (0 === i) return [[obj]];
if (obj.type === newAr[newAr.length - 1][0].type)
return newAr[newAr.length - 1].push(obj), newAr;
return [...newAr, [obj]];
}, []);
const groupedAr = group(arrayObj);
console.log(groupedAr);
function groupConsecutive(arrayObj) {
if (arrayObj.length === 0) {
return [];
}
let matchedTypesIndex = 0;
let newArray = [
[
arrayObj[0]
]
];
let currentType = arrayObj[0]["type"];
let i = 1;
while (i < arrayObj.length) {
if (arrayObj[i]["type"] === currentType) {
newArray[matchedTypesIndex].push(arrayObj[i]);
} else {
currentType = arrayObj[i]["type"];
newArray.push([]);
matchedTypesIndex++;
newArray[matchedTypesIndex].push(arrayObj[i]);
}
i++;
}
return newArray;
}
This is probably not best pure solution but works as you need.
var arrayObj = [
{ "type": "user", "text": "user1" },
{ "type": "user", "text": "user2" },
{ "type": "user", "text": "user3" },
{ "type": "clerk", "text": "clerk1" },
{ "type": "user", "text": "user4" },
{ "type": "clerk", "text": "clerk2" },
{ "type": "clerk", "text": "clerk3" },
{ "type": "user", "text": "user5" },
{ "type": "user", "text": "user6" }
];
let lastType;
let arr = [];
let arrIndex = -1;
arrayObj.forEach(obj => {
if(obj.type == lastType) { // add item into last group array by index
arr[arrIndex].push(obj);
}
else { // or add new group array
lastType = obj.type;
arrIndex++;
arr.push([obj]);
}
})
console.log(arr);
See This solution it will work
var arrayObj = [
{ type: "user", text: "user1" },
{ type: "user", text: "user2" },
{ type: "user", text: "user3" },
{ type: "clerk", text: "clerk1" },
{ type: "user", text: "user4" },
{ type: "clerk", text: "clerk2" },
{ type: "clerk", text: "clerk3" },
{ type: "user", text: "user5" },
{ type: "user", text: "user6" },
];
let typeNow = arrayObj[0].type;
let res = [];
let resultArray = [];
arrayObj.forEach((obj, i) => {
if (obj.type == typeNow) {
resultArray.push(obj);
} else {
resultArray = [obj];
res.push(resultArray);
typeNow = obj.type;
}
if (i == arrayObj.length - 1) res.push(resultArray);
});
console.log(res);
This is best solution can i have
It seem unordred because of Browser auto order but if you try in js file it will work and ordred
I'm responding with another way I found to solve my problem. This is just one more way I decided to comment.
Let's go:
I'm traversing the arrayObjects array using the appropriate loop for arrays for...of and then checking if the variable I set for arrayObjects (loopArrObj) has a different value of type of the variable (typeValue), if it is inserted at the end of the new array (grouping) using the array method push an empty array and then assign the value of the loopArrObj(Ie, there will be in the array grouping array empty only for the values that are different).
So far so good, we have the first empty array. Next I'm defining this empty array with the push method the loopArrObj object in question, then we get the value through the console. I'm removing 1 from grouping.lengh so the loop assigns from 0 and not 1.
var arrayObjects = [
{ "type": "user", "text": "user1" },
{ "type": "user", "text": "user2" },
{ "type": "user", "text": "user3" },
{ "type": "clerk", "text": "clerk1" },
{ "type": "user", "text": "user4" },
{ "type": "clerk", "text": "clerk2" },
{ "type": "clerk", "text": "clerk3" },
{ "type": "user", "text": "user5" },
{ "type": "user", "text": "user6" }
];
let typeValue,
grouping = [],
loopArrObj;
for (loopArrObj of arrayObjects) {
if (loopArrObj.type !== typeValue) {
grouping.push([]);
typeValue = loopArrObj.type;
}
grouping[grouping.length - 1].push(loopArrObj);
}
console.log(grouping);
I have a JSON with lots of empty content:
{
"items": [
{
"category": "login",
"fields": [
{
"label": "Name",
"value": "",
},
{
"label": "E-Mail",
"value": "",
},
{
"label": "Password",
"value": "123456",
},
{
"label": "Website",
"fields": [
{
"label": "Name X",
"value": ""
},
{
"label": "Name Y",
"value": "another one"
},…
]
},…
]
},…
]
}
The nesting goes several levels deeper. This shows only the first level. I want to delete all elements of "fields" (or whatever the array's key in deeper levels is), where their "value" is empty.
{
"items": [
{
"category": "login",
"fields": [
{
"label": "Password",
"value": "123456",
},
{
"label": "Website",
"fields": [
{
"label": "Name Y",
"value": "another one"
},…
]
},…
]
},…
]
}
How can I do this in Javascript?
Well, I found a way to iterate through the JSON object:
function remove(jsondata) {
for (let i in jsondata) {
if (jsondata[i].value != undefined && jsondata[i].value == '') {
delete jsondata[i];
}
else if (typeof jsondata[i] === "object") remove(jsondata[i]);
}
}
Not sure, if it's the most elegant way, but it works so far.
use filter method,you could get a filtered array
it returned Boolean. if value exist,it will be true
var list=JSON.parse(data)
list.items=list.items.map(val=>{
val.fields=val.fields.filter(v=>v.value})
return val
})
We use object-scan for many data processing tasks. It's powerful once you wrap your head around it. Here is how you could answer your questions
// const objectScan = require('object-scan');
const prune = (input) => objectScan(['**[*].value'], {
rtn: 'count',
filterFn: ({ gparent, gproperty, value }) => {
if (value === '') {
gparent.splice(gproperty, 1);
return true;
}
return false;
}
})(input);
const obj = { items: [{ category: 'login', fields: [{ label: 'Name', value: '' }, { label: 'E-Mail', value: '' }, { label: 'Password', value: '123456' }, { label: 'Website', fields: [{ label: 'Name X', value: '' }, { label: 'Name Y', value: 'another one' }] }] }] };
console.log(prune(obj)); // return count of pruned entries
// => 3
console.log(obj);
// => { items: [ { category: 'login', fields: [ { label: 'Password', value: '123456' }, { label: 'Website', fields: [ { label: 'Name Y', value: 'another one' } ] } ] } ] }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#16.0.0"></script>
Disclaimer: I'm the author of object-scan
I have got two arrays of objects. I want to filter data based on permissionObj.
This is coming from database. Here are arrays of sub-arrays in the permissionObj.
I need to do another condition in reduce function . For example , if Pubsidebar value is token is public, I want to keep static content {label: "test",value: "public"} without filtering with permissionObj and if other key and value is match with permissionObj,then it will be push inside token .
let permissionObj = [
{
'OA deal': [
{
label: 'can view',
value: 'can_view',
},
],
},
{
Deposit: [
{
label: 'can edit',
value: 'can_edit',
},
],
},
{
Deposit: [
{
label: 'can_view',
value: 'can_view',
},
],
},
{
Journals: [
{
label: 'can create',
value: 'can_create',
},
],
},
{
Dashboard: [
{
label: 'can view',
value: 'can_view',
},
],
},
{
token: [
{
label: 'can view',
value: 'can_create',
},
],
},
]
const PubSidebar = [
{
label: 'Dashboard',
value: 'can_view',
},
{
label: 'token',
value: 'public',
content: [
{
key: 'token',
value: 'can_create',
},
{
key: 'test',
value: 'public',
},
],
},
{
label: 'OA deal',
content: [
{
label: 'view oadeal',
key: 'OA deal',
value: 'can_view',
},
{
label: 'Deposit',
key: 'Deposit',
value: 'can_view',
},
{
label: 'Corrections',
key: 'Corrections',
value: 'can_edit',
},
],
},
{
label: 'Journals',
content: [
{
label: 'Add Journal',
key: 'Journals',
value: 'can_create',
},
],
},
]
const filterObject = permissionObj.reduce((a, c) => {
for (const key in c) {
a[key] = c[key]
}
return a
}, {})
const result = PubSidebar.reduce((a, c) => {
if (
filterObject[c.label] &&
c.value &&
filterObject[c.label].some(s => s.value === c.value)
) {
a.push(c)
} else if (c.value === 'public' && c.label === 'token') {
if (
(c.content = c.content.filter(
f =>
filterObject[f.key] &&
filterObject[f.key].some(s => s.value == f.value)
))
) {
c.content = c.content.filter(
f =>
filterObject[f.key] &&
filterObject[f.key].some(s => s.value == f.value)
)
a.push(c)
}
} else if (c.content.some(s => filterObject[s.key]) && c.content) {
c.content = c.content.filter(
f =>
filterObject[f.key] && filterObject[f.key].some(s => s.value == f.value)
)
a.push(c)
}
return a
}, [])
console.log(result)
Here is code snippet . I am trying to getting public data from sidebar without filtering with permissionObj.
my expected output would :
[
{
"label": "Dashboard",
"value": "can_view"
},
{
"label": "token",
"value": "public",
"content": [{
"key": "test",
"value": "public"
}
{
"key": "token",
"value": "can_create"
}
]
},
{
"label": "OA deal",
"content": [
{
"label": "view oadeal",
"key": "OA deal",
"value": "can_view"
},
{
"label": "Deposit",
"key": "Deposit",
"value": "can_view"
}
]
},
{
"label": "Journals",
"content": [
{
"label": "Add Journal",
"key": "Journals",
"value": "can_create"
}
]
}
]
I have two arrays of objects
const reference_array= [{"key":"oAuthAccessToken","label":"Access Token","value":""},{"key":"clientId","label":"Client ID","value":""},{"label":"Verification Token","key":"verificationToken","value":""},{"label":"User ID","key":"userId","value":""},{"key":"signingSecret","label":"Signing Secret","value":""},{"label":"App ID","key":"appId","value":""},{"label":"Team ID","key":"teamId","value":""},{"label":"Name","key":"name","value":""},{"label":"Client Secret","key":"clientSecret","value":""},{"label":"ID","key":"id","value":""},{"label":"Channel ID","key":"channelId","value":""},{"key":"","value":""}]
const resArray = [{"key":"3111","value":"12111"},{"key":"656556","value":"55666664"},{"key":"oAuthAccessToken","value":"123"},{"key":"clientId","value":"5"},{"key":"webhook_URL","value":"https://api.slack.com/1.1/account_activity/all/dev/webhooks.json?ref=7364616106833455"},{"key":"verificationToken","value":"55525"},{"key":"userId","value":"254"},{"key":"createdDate","value":"2019-09-05T07:47:24Z"},{"key":"createdBy","value":"John"},{"key":"webhook_ID","value":"7364616106833455"},{"key":"signingSecret","value":"12476233"},{"key":"appId","value":"9886"},{"key":"teamId","value":"8955653563"},{"key":"name","value":"56565"},{"key":"clientSecret","value":"656665656"},{"key":"id","value":"5656565"},{"key":"channelId","value":"55655565"}]
I would like to sort the resArray based on order of reference_array, the similar things of the two arrays is key value.
How to sort the resArray based on order of reference_array.
I tried in many ways but i have no luck.please help me to resolve the issue like below
Thanks in advance
resArray.sort(function(a, b) {
return reference_array.map(function(x) {return x.key; }).indexOf(b) - reference_array.map(function(x) {return x.key; }).indexOf(a);
});
Expected Output :
const resArray = [{
"key": "oAuthAccessToken",
"value": "123"
}, {
"key": "clientId",
"value": "5"
}, {
"key": "verificationToken",
"value": "55525"
}, {
"key": "userId",
"value": "254"
}, {
"key": "signingSecret",
"value": "12476233"
}, {
"key": "appId",
"value": "9886"
}, {
"key": "teamId",
"value": "8955653563"
}, {
"key": "name",
"value": "56565"
}, {
"key": "clientSecret",
"value": "656665656"
}, {
"key": "id",
"value": "5656565"
}, {
"key": "channelId",
"value": "55655565"
}, {
"key": "3111",
"value": "12111"
}, {
"key": "656556",
"value": "55666664"
}, {
"key": "webhook_URL",
"value": "https://api.slack.com/1.1/account_activity/all/dev/webhooks.json?ref=7364616106833455"
}, {
"key": "createdDate",
"value": "2019-09-05T07:47:24Z"
}, {
"key": "createdBy",
"value": "John"
},
{
"key": "webhook_ID",
"value": "7364616106833455"
}
]
You could take an object as reference for the sorting order and take Infinity for unknown key for sorting this items to the bottom of the array.
var reference = [{ key: "oAuthAccessToken", label: "Access Token", value: "" }, { key: "clientId", label: "Client ID", value: "" }, { label: "Verification Token", key: "verificationToken", value: "" }, { label: "User ID", key: "userId", value: "" }, { key: "signingSecret", label: "Signing Secret", value: "" }, { label: "App ID", key: "appId", value: "" }, { label: "Team ID", key: "teamId", value: "" }, { label: "Name", key: "name", value: "" }, { label: "Client Secret", key: "clientSecret", value: "" }, { label: "ID", key: "id", value: "" }, { label: "Channel ID", key: "channelId", value: "" }, { key: "", value: "" }],
array = [{ key: "3111", value: "12111" }, { key: "656556", value: "55666664" }, { key: "oAuthAccessToken", value: "123" }, { key: "clientId", value: "5" }, { key: "webhook_URL", value: "https://api.slack.com/1.1/account_activity/all/dev/webhooks.json?ref=7364616106833455" }, { key: "verificationToken", value: "55525" }, { key: "userId", value: "254" }, { key: "createdDate", value: "2019-09-05T07:47:24Z" }, { key: "createdBy", value: "John" }, { key: "webhook_ID", value: "7364616106833455" }, { key: "signingSecret", value: "12476233" }, { key: "appId", value: "9886" }, { key: "teamId", value: "8955653563" }, { key: "name", value: "56565" }, { key: "clientSecret", value: "656665656" }, { key: "id", value: "5656565" }, { key: "channelId", value: "55655565" }],
order = reference.reduce((o, { key }, i) => (o[key] = i + 1, o), {});
array.sort((a, b) => (order[a.key] || Infinity) - (order[b.key] || Infinity));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }