How to Decode logs data of transaction? - javascript

I want decode logs data, I am using web3.utils.hexToAscii() method which return junk data like !3cÀ Token create101 insted of actual data 2000 Token create 101.
> {
transactionHash: '0x0d2a00b4d684efbdea26677468830d88b2145577a4b086775ebdb5189ed78d27',
transactionIndex: 0,
blockHash: '0x702e444fba974d17a9b8e881c8002e721c0517ea254991884d2ef745b7510126',
blockNumber: 2,
from: '0x21003381639c90b61ef0b1ad692078c4ee3d0a7f',
to: '0x42eb248f2dc51d6dbc13e92aed4be07291373b90',
gasUsed: 26567,
cumulativeGasUsed: 26567,
contractAddress: null,
logs: [
> {
logIndex: 0,
transactionIndex: 0,
transactionHash: '0x0d2a00b4d684efbdea26677468830d88b2145577a4b086775ebdb5189ed78d27',
blockHash: '0x702e444fba974d17a9b8e881c8002e721c0517ea254991884d2ef745b7510126',
blockNumber: 2,
address: '0x42EB248f2DC51D6dBc13e92Aed4bE07291373B90',
data: '0x00000000000000000000000021003381639c90b61ef0b1ad692078c4ee3d0a7f00000000000000000000000000000000000000000000000000000000000000c8000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000000c546f6b656e20637265617465000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000033130310000000000000000000000000000000000000000000000000000000000',
topics: [Array],
type: 'mined',
id: 'log_985c3fd6'
> }
> ],
status: true,
logsBloom: '0x00000000000000000000000000000000000000800000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000'
> }
I have tried below code but its return junk data.
function checkHex(){
var block = web3.eth.getBlock('latest')
block.then(block => {
for(let txHash of block.transactions){
let tx = web3.eth.getTransaction(txHash);
tx.then(tx => {
let receipt = web3.eth.getTransactionReceipt(tx.hash);
receipt.then(receipt => {
for(let logs of receipt.logs){
const decoded = web3.utils.hexToAscii(logs.data);
console.log(decoded);
> }
> });
> });
> }
> });
> }
return
!3cÀ Token create101
expected
2000 Token create 101

Related

Filter nested array in object javascript express

Considering the below object:
[
{
id: 5fc0be2990a8a12cc0ba0b5c,
projectName: 'E-271120-B',
projectManagaer: '5f7f1ba973ff621da4322248',
dataInici: 2020-11-26T23:00:00.000Z,
dataEntrega: 2020-11-26T23:00:00.000Z,
dtoGlobal: null,
dtoProjecte: null,
archived: false,
created: 2020-11-27T08:51:57.242Z,
updated: 2021-01-25T10:01:18.733Z
tabs: [{permissionsUserID:[250,8]},{permissionsUserID:[3]}],
__v: 3
},
{
tabs: [{permissionsUserID:[3,350]},{permissionsUserID:[15]}],
_id: 5fc0be4690a8a12cc0ba0b5f,
projectManagaer: '5f7f0e69b5862e1a085db388',
projectName: 'E-271120-C',
dataInici: 2020-11-27T23:00:00.000Z,
dataEntrega: 2020-11-29T23:00:00.000Z,
dtoGlobal: null,
dtoProjecte: null,
archived: false,
created: 2020-01-21T08:46:41.958Z,
updated: 2021-01-21T08:46:41.958Z,
__v: 2
},
{
tabs: [{permissionsUserID:[31,350]},{permissionsUserID:[8,893]}],
_id: 5fc0be4690a8a12cc0ba0b5f,
projectManagaer: '5f7f0e69b5862e1a085db388',
projectName: 'E-23410-C',
dataInici: 2020-11-27T23:00:00.000Z,
dataEntrega: 2020-11-29T23:00:00.000Z,
dtoGlobal: null,
dtoProjecte: null,
archived: false,
created: 2020-01-21T08:46:41.958Z,
updated: 2021-01-21T08:46:41.958Z,
__v: 2
}
]
Each object represents a Project. A project has many tabs.
I want to return only the projects that at least one tab contains in permissionsUserID the ID of the user that is logged.
So if the user that is logged has the ID 8, these are the projects I want to obtain:
[
{
id: 5fc0be2990a8a12cc0ba0b5c,
projectName: 'E-271120-B',
projectManagaer: '5f7f1ba973ff621da4322248',
dataInici: 2020-11-26T23:00:00.000Z,
dataEntrega: 2020-11-26T23:00:00.000Z,
dtoGlobal: null,
dtoProjecte: null,
archived: false,
created: 2020-11-27T08:51:57.242Z,
updated: 2021-01-25T10:01:18.733Z
tabs: [{permissionsUserID:[250,8]},{permissionsUserID:[3]}],
__v: 3
},
{
tabs: [{permissionsUserID:[31,350]},{permissionsUserID:[8,893]}],
_id: 5fc0be4690a8a12cc0ba0b5f,
projectManagaer: '5f7f0e69b5862e1a085db388',
projectName: 'E-23410-C',
dataInici: 2020-11-27T23:00:00.000Z,
dataEntrega: 2020-11-29T23:00:00.000Z,
dtoGlobal: null,
dtoProjecte: null,
archived: false,
created: 2020-01-21T08:46:41.958Z,
updated: 2021-01-21T08:46:41.958Z,
__v: 2
}
]
That's the filter I have done:
async getAll(pagination, user) {
try {
const filter = {};
if(pagination.archived) {
filter['archived'] = pagination.archived;
}
if(pagination.search) {
filter['$text'] = {$search: pagination.search}
}
const { Project: projectSchema } = this.getSchemas();
const projectsDocs = await projectSchema.paginate(filter, {
limit: pagination.limit ? parseInt(pagination.limit) : 10,
page: pagination.page ? parseInt(pagination.page) + 1 : 1
});
if (!projectsDocs) {
throw new errors.NotFound('No Projects.');
}
projectsDocs.docs.forEach(element => {
element.tabs.filter( d => d.permissionsUserID.every( c => c.includes(user._id)));
});
return projectsDocs;
} catch (error) {
throw error;
}
},
Here is one way
const data = [...];
const userId = 8;
const result = data.filter((item) => {
const {tabs} = item;
let loggedIn = false;
tabs.forEach((tab) => {
if (tab.permissionsUserID.includes(userId)) {
loggedIn = true;
return true
}
})
return loggedIn;
})
Here's a simple function which should get you what you want.
Filter() returns a subset of the projects list. Some() returns true if at least one of the tabs has the value we're looking for. Includes() returns true if the permissionsUserId list has the user id we want. Chain those together and you get the subset of projects where a tab's permissions has the desired user id.
const data = [
/* list of projects */
],
userId = 8;
function getProjectsForUserId (data, userId) {
return data.filter((project) => {
return project.tabs.some((tab) => {
return tab.permissionsUserID.includes(userId);
});
});
}
console.log(getProjectsForUserId(data, 8));

How to use map function on a json response in javascript?

I am using zomato API to find a random restaurant within an area. This is the API call.
app.post('/locations/:query', async (req, res) =>
{
try{
const query = req.params.query;
const data = await zomato.cities({ q: query,count: 1 })
const cityId= await (data[0].id);
const result = [];
const nrOfRequests = 60;
let currCount = 0;
const nrOfEntries = 20;
for(let i=0; i < nrOfRequests ; i++) {
const response = await zomato.search({ entity_id: cityId, entity_type: 'city', start:currCount, count:nrOfEntries, sort:'rating', order:'desc' });
result.push(...response.restaurants);
currCount += nrOfEntries;
}
const no = Math.floor(Math.random() * 60);
const restaur = result[no].restaurants.map(r => {
return {
name: r.name,
url: r.url,
location: r.location,
price: r.price_range,
thumbnail: r.thumb,
rating: r.user_rating.aggregate_rating,
}
})
res.send({restaur});
} catch (err) {
console.error(err)
res.status(500).send('error')
}
});
What this API is doing is
1)Finds cityId of query.(query is a city name)
2)Using for loop finds upto 60 restaurants in that city according to rating and pushes it in results[].(zomato api has restriction to display only 20 restaurants per call)
3)Chooses a random number between 0 to 60 and outputs that particular restaurant from result.
4)Then what I want to do is find features like name price etc and return to display that in the frontend.
Using this code I get the following error
TypeError: Cannot read property 'map' of undefined
The result[no] response looks like this.
{
R: {
has_menu_status: { delivery: -1, takeaway: -1 },
res_id: 302578,
is_grocery_store: false
},
apikey: '*************',
id: '302578',
name: 'Barbeque Nation',
url: 'https://www.zomato.com/ncr/barbeque-nation-saket-new-delhi?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1',
location: {
address: 'M/A 04, DLF Avenue, District Centre, Saket, New Delhi',
locality: 'DLF Avenue, Saket',
city: 'New Delhi',
city_id: 1,
latitude: '28.5273432339',
longitude: '77.2173847631',
zipcode: '',
country_id: 1,
locality_verbose: 'DLF Avenue, Saket, New Delhi'
},
switch_to_order_menu: 0,
cuisines: 'North Indian, BBQ, Beverages',
timings: '12noon – 3:30pm, 6pm – 11pm (Mon-Sun)',
average_cost_for_two: 1600,
price_range: 3,
currency: 'Rs.',
highlights: [
'Lunch',
'Serves Alcohol',
'Mall Parking',
'Cash',
'Credit Card',
'Debit Card',
'Dinner',
'Takeaway Available',
'Fullbar',
'Indoor Seating',
'Air Conditioned',
'Reopened',
'Buffet'
],
offers: [],
opentable_support: 0,
is_zomato_book_res: 0,
mezzo_provider: 'OTHER',
is_book_form_web_view: 0,
book_form_web_view_url: '',
book_again_url: '',
thumb: 'https://b.zmtcdn.com/data/pictures/chains/2/1212/b6429ddad24625e65344caabb921bd57.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A',
user_rating: {
aggregate_rating: '4.7',
rating_text: 'Excellent',
rating_color: '3F7E00',
rating_obj: { title: [Object], bg_color: [Object] },
votes: 2248
},
all_reviews_count: 1159,
photos_url: 'https://www.zomato.com/ncr/barbeque-nation-saket-new-delhi/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop',
photo_count: 1991,
menu_url: 'https://www.zomato.com/ncr/barbeque-nation-saket-new-delhi/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop',
featured_image: 'https://b.zmtcdn.com/data/pictures/chains/2/1212/b6429ddad24625e65344caabb921bd57.jpg',
medio_provider: 1,
has_online_delivery: 1,
is_delivering_now: 0,
store_type: '',
include_bogo_offers: true,
deeplink: 'zomato://restaurant/302578',
is_table_reservation_supported: 1,
has_table_booking: 0,
events_url: 'https://www.zomato.com/ncr/barbeque-nation-saket-new-delhi/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1',
phone_numbers: '080 61756005',
all_reviews: { reviews: [ [Object], [Object], [Object], [Object], [Object] ] },
establishment: [ 'Casual Dining' ],
establishment_types: []
}
The results[no] that you're showing indeed has no property called restaurants. You have an array called results, and you're selecting a single element from that array. When you have a single element, there's nothing to "map".
Instead, just return the fields you want from that element:
const no = Math.floor(Math.random() * 60);
const restaur = {
name: result[no].name,
url: result[no].url,
location: result[no].location,
price: result[no].price_range,
thumbnail: result[no].thumb,
rating: result[no].user_rating.aggregate_rating,
};
res.send(restaur);

why insertmany not working using mongoos with transactions?

I am trying to insert data using inertMany .but I am not able to insert the data why ?I am using mongoose session if any error occurred then I roll back changes
https://codesandbox.io/s/dreamy-bell-9u0bz
app.get("/saveData", async (req, res, next) => {
const session = await mongoose.startSession();
session.startTransaction();
try {
const data = [
{
empid: "Ad",
id: 4,
date: "19-Jul-2019"
},
{
empid: "Bc",
id: 56,
date: "18-Jul-2019"
},
{
empid: "C",
id: 6,
date: "11-Jul-2019"
}
];
console.log("before save");
let saveBlog = await BlogPostModel.insertMany(data, { session }); //when fail its goes to catch
await session.commitTransaction();
return res.send(saveBlog);
} catch (error) {
console.log(error);
await session.abortTransaction();
return res.status(400).send(error);
}
});
Since you don't appear to have understood the marked duplicate or the comment on your last question, here's a direct demonstration:
const { Schema } = mongoose = require('mongoose');
const uri = 'mongodb://localhost:27017/test';
const opts = { useNewUrlParser: true, useUnifiedTopology: true };
mongoose.Promise = global.Promise;
mongoose.set('debug', true);
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);
const blogPostSchema = new Schema({
id: { type: Number, unique: true },
empid: String,
date: Date
});
const BlogPost = mongoose.model('BlogPost', blogPostSchema);
const sampleData = [
{ empid: "test13", id: 6, date: '11-Jul-2019' },
{ empid: "test123", id: 4, date: '19-Jul-2019' },
{ empid: "test13", id: 4, date: '18-Jul-2019' }
];
const log = data => console.log(JSON.stringify(data, undefined, 2));
(async function() {
try {
const conn = await mongoose.connect(uri, opts);
// Clean data
await Promise.all(
Object.values(conn.models).map(m => m.deleteMany())
);
// Collections must existi in transactions
await Promise.all(
Object.values(conn.models).map(m => m.createCollection())
);
// With Transaction
log("With Transaction");
let session = await conn.startSession();
session.startTransaction();
try {
await BlogPost.insertMany(sampleData, { session });
await session.commitTransaction();
} catch(e) {
// Show the error and abort
log({ err: e.errmsg, result: e.result.result.writeErrors });
await session.abortTransaction();
}
log({ results: (await BlogPost.find()) });
// No transaction
log("Without Transaction");
try {
await BlogPost.insertMany(sampleData);
} catch(e) {
// Show the error
log({ err: e.errmsg, result: e.result.result.writeErrors });
}
log({ results: (await BlogPost.find()) });
} catch (e) {
console.error(e);
} finally {
mongoose.disconnect();
}
})();
And the output:
Mongoose: blogposts.createIndex({ id: 1 }, { unique: true, background: true })
Mongoose: blogposts.deleteMany({}, {})
"With Transaction"
Mongoose: blogposts.insertMany([ { _id: 5d8f28ac462a1e1a8c6838a2, empid: 'test13', id: 6, date: 2019-07-10T14:00:00.000Z, __v: 0 }, { _id: 5d8f28ac462a1e1a8c6838a3, empid: 'test123', id: 4, date: 2019-07-18T14:00:00.000Z, __v: 0 }, { _id: 5d8f28ac462a1e1a8c6838a4, empid: 'test13', id: 4, date: 2019-07-17T14:00:00.000Z, __v: 0 } ], { session: ClientSession("650da06d23544ef8bc1d345d93331d1e") })
{
"err": "E11000 duplicate key error collection: test.blogposts index: id_1 dup key: { id: 4 }",
"result": [
{
"code": 11000,
"index": 2,
"errmsg": "E11000 duplicate key error collection: test.blogposts index: id_1 dup key: { id: 4 }",
"op": {
"_id": "5d8f28ac462a1e1a8c6838a4",
"empid": "test13",
"id": 4,
"date": "2019-07-17T14:00:00.000Z",
"__v": 0
}
}
]
}
Mongoose: blogposts.find({}, { projection: {} })
{
"results": []
}
"Without Transaction"
Mongoose: blogposts.insertMany([ { _id: 5d8f28ac462a1e1a8c6838a5, empid: 'test13', id: 6, date: 2019-07-10T14:00:00.000Z, __v: 0 }, { _id: 5d8f28ac462a1e1a8c6838a6, empid: 'test123', id: 4, date: 2019-07-18T14:00:00.000Z, __v: 0 }, { _id: 5d8f28ac462a1e1a8c6838a7, empid: 'test13', id: 4, date: 2019-07-17T14:00:00.000Z, __v: 0 } ], {})
{
"err": "E11000 duplicate key error collection: test.blogposts index: id_1 dup key: { id: 4 }",
"result": [
{
"code": 11000,
"index": 2,
"errmsg": "E11000 duplicate key error collection: test.blogposts index: id_1 dup key: { id: 4 }",
"op": {
"_id": "5d8f28ac462a1e1a8c6838a7",
"empid": "test13",
"id": 4,
"date": "2019-07-17T14:00:00.000Z",
"__v": 0
}
}
]
}
Mongoose: blogposts.find({}, { projection: {} })
{
"results": [
{
"_id": "5d8f28ac462a1e1a8c6838a5",
"empid": "test13",
"id": 6,
"date": "2019-07-10T14:00:00.000Z",
"__v": 0
},
{
"_id": "5d8f28ac462a1e1a8c6838a6",
"empid": "test123",
"id": 4,
"date": "2019-07-18T14:00:00.000Z",
"__v": 0
}
]
}
Note that when the transaction is in use there are no items inserted into the collection. Using the insertMany() with the default behavior of ordered: true will insert all batched items up until the point any error is encountered.
Note also as stated since you are indeed expecting an error you must include such a statement in it very own try..catch or similar error handler. Otherwise any error ( which is expected in the example case ) would simply fall to the outer catch, which of course in the demonstration simply exits the program.
Not actually in the question itself but something not actually mentioned in the demonstrations of How to use MongoDB transaction using Mongoose? is indeed that you should be aware that whlist a transaction is active you must also include the session attribute on any subsequent reads in order to see the changes made within that transaction.
For instance, the following would show no content in a collection:
let session = await conn.startSession();
session.startTransaction();
try {
await BlogPost.insertMany(sampleData, { session });
let documents = await BlogPost.find(); // This would return nothing
await session.commitTransaction();
} catch(e) {
// Show the error and abort
log({ err: e.errmsg, result: e.result.result.writeErrors });
await session.abortTransaction();
}
However including the session within a find() will actually show what is inserted:
try {
await BlogPost.insertMany(sampleData, { session });
// Actually includes the session and therefore the state
let documents = await BlogPost.find({},{ session });
await session.commitTransaction();
} catch(e) {
// Show the error and abort
log({ err: e.errmsg, result: e.result.result.writeErrors });
await session.abortTransaction();
}
And of course that read would in this case be dependent on the insertMany() not failing for any reason, since any error would result in exiting to the catch before the next request was made.
Once a transaction is committed, it is of course available to the global state of the connection. But whilst in progress only operations which include the same session information on which the transaction was started will have visibility of any changes implemented within that transaction.
For who get the error "Cannot read property 'map' of undefined" while passing session as option in inserMany, this errors come because your mongo is running as standalone servers, to fix this can refer npm package run-rs or following this answer to fix this: https://stackoverflow.com/a/60603587/9611273

node.js looping database inserts

I have an application, with an address object, and a list of people associated with the application.
{
field1: value,
field2: value,
address: {
street: value,
apt: value,
city: value
},
owners: [
{name: value, etc.},
{name: value, etc.}
]
}
I am passing the owners off to a function that loops over the owners and passes the information for each query off to an async function:
async function insertAllOwners(appId, owners) {
for (var i = 0, len = owners.length; i < len; i++) {
console.log("insert owner", i);
await insertOwner(appId, owners[i]);
}
}
The function being called here turns the query into a promise:
function insertOwner(appId, owner) {
let sqlOwner = 'insert into ...';
return new Promise( ( resolve, reject ) => {
mySqlClient.query(sqlOwner, [appId, owner.memberType ...], (err, rows) => {
if ( err )
return reject( err );
console.log("rows:", rows);
resolve( rows );
} );
} );
}
The address insert is nested inside the application insert, then the code that calls the owner insert loop is nested inside the address insert. The looping owner insert function is called here:
if(app.owners) {
/* insert owners, then commit. else, just commit.*/
insertAllOwners(appId, app.owners).then( result => {
mySqlClient.commit(function(err, result) {
if (err) {
console.error("ERROR DURING COMMIT:", err);
mySqlClient.rollback(function() {
throw err;
});
}
else {
console.log("commit:",result);
}
});
});
}
The output looks perfect, but it doesn't appear to actually commit anything (the new rows are not showing up). Any suggestions? Output of logging is below:
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 1,
warningCount: 1,
message: '',
protocol41: true,
changedRows: 0
}
address result:
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 35,
serverStatus: 1,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
insert owner 0
rows:
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 70,
serverStatus: 1,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
...
insert owner 4
rows:
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 74,
serverStatus: 1,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
commit:
OkPacket {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverStatus: 0,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
The first thing is that , this is not a good practice to execute a query.
what you are doing to run a for loop and each loop execute each query. Bu this way you give load to mysql. And also it will take longer time execute your API.
I suggest this way.
In for loop :
for (var i = 0, len = owners.length; i < len; i++) {
inserData.push(owners[i]); // Add all data in to array ...
}
After that execute query once with all data.
connection.query("INSERT INTO TABLE (columns) VLAUES ? " , insertData)...

Ordering the JSON data with JavaScript

I'm looking way to order data wich is coming from my JSON Provider:
[{"Username":"Mehmet","UserID":2,"OkeyTablePlayerChairNumber":1},
{"Username":null,"UserID":0,"OkeyTablePlayerChairNumber":2},
{"Username":"Erçin","UserID":1,"OkeyTablePlayerChairNumber":3},
{"Username":null,"UserID":0,"OkeyTablePlayerChairNumber":4},
{"Username":null,"UserID":0,"OkeyTablePlayerChairNumber":5},
{"Username":null,"UserID":0,"OkeyTablePlayerChairNumber":6},
{"Username":null,"UserID":0,"OkeyTablePlayerChairNumber":7},
{"Username":null,"UserID":0,"OkeyTablePlayerChairNumber":8},
{"Username":null,"UserID":0,"OkeyTablePlayerChairNumber":9}]
There is two more important thing for ordering:
OkeyTablePlayerChairNumber
By UserID First; let me explain:
I want to order them firstly by OkeyTableChairNumber; this is done by Server Side already. Data coming ordered by OkeyTablePlayerChairNumber ASC...
Now the bull,
I would like to order them by UserID but; for example if I took UserID == 1 it should order them like: UserID == 1 field, will be come to first field. and upper objects will removed and added to end of the list...
For view:
UserID == 1
[{"Username":"Erçin","UserID":1,"OkeyTablePlayerChairNumber":3},
{"Username":null,"UserID":0,"OkeyTablePlayerChairNumber":4},
{"Username":null,"UserID":0,"OkeyTablePlayerChairNumber":5},
{"Username":null,"UserID":0,"OkeyTablePlayerChairNumber":6},
{"Username":null,"UserID":0,"OkeyTablePlayerChairNumber":7},
{"Username":null,"UserID":0,"OkeyTablePlayerChairNumber":8},
{"Username":null,"UserID":0,"OkeyTablePlayerChairNumber":9},
{"Username":"Mehmet","UserID":2,"OkeyTablePlayerChairNumber":1},
{"Username":null,"UserID":0,"OkeyTablePlayerChairNumber":2}]
C# Solution I made before; But I need JS solutions:
int yourSitPositionIndex = playersOnTheTableWithEmpytPositions.ToList().FindIndex(x => x.UserID == userID);
var beforePlayers = playersOnTheTableWithEmpytPositions.ToList().GetRange(0, yourSitPositionIndex);
IEnumerable<tbl_Okey_TablePlayer> afterPlayers = playersOnTheTableWithEmpytPositions.Except(beforePlayers);
IEnumerable<tbl_Okey_TablePlayer> newPositions = afterPlayers.Concat(beforePlayers);
Conversion of your C# solution:
var wantedId = 1;
var index = 0, result;
//int yourSitPositionIndex = playersOnTheTableWithEmpytPositions.ToList().FindIndex(x => x.UserID == userID);
while (index < data.length && data[index].UserID != wantedId) index += 1;
if (index < data.length) {
//var beforePlayers = playersOnTheTableWithEmpytPositions.ToList().GetRange(0, yourSitPositionIndex);
var beforePlayers = data.slice(0, index);
//IEnumerable<tbl_Okey_TablePlayer> afterPlayers = playersOnTheTableWithEmpytPositions.Except(beforePlayers);
var afterPlayers = data.slice(index);
//IEnumerable<tbl_Okey_TablePlayer> newPositions = afterPlayers.Concat(beforePlayers);
result = afterPlayers.concat(beforePlayers);
} else {
result = data;
}
There is no FindIndex in the core of javascript, so I did a while loop to find the index
I use .slice() to replace GetRange
Rest of the code should be clear enough. The all code could be simplified with libraries like underscore
Example fiddle
If the goal is to order by UserID DESC, OkeyTable... ASC
You can define a customer sort function:
In action: http://repl.it/XZm
var json = [/*all your data */]
function idSort(a,b){
if(a["UserID"] !== b["UserID"]){
return b["UserID"] - a["UserID"];
} else {
return a["OkeyTablePlayerChairNumber"] - b["OkeyTablePlayerChairNumber"];
}
}
var sorted = json.sort(idSort);
Results:
[ { Username: 'Mehmet', UserID: 2, OkeyTablePlayerChairNumber: 1 },
{ Username: 'Erçin', UserID: 1, OkeyTablePlayerChairNumber: 3 },
{ Username: null, UserID: 0, OkeyTablePlayerChairNumber: 2 },
{ Username: null, UserID: 0, OkeyTablePlayerChairNumber: 4 },
{ Username: null, UserID: 0, OkeyTablePlayerChairNumber: 5 },
{ Username: null, UserID: 0, OkeyTablePlayerChairNumber: 6 },
{ Username: null, UserID: 0, OkeyTablePlayerChairNumber: 7 },
{ Username: null, UserID: 0, OkeyTablePlayerChairNumber: 8 },
{ Username: null, UserID: 0, OkeyTablePlayerChairNumber: 9 } ]
Here is UserID ASC, OkeyTable...ASC:
function idSort(a,b){
var notZero = (a["UserID"] > 0 && b["UserID"] > 0);
var notEqual = (a["UserID"] !== b["UserID"]);
if(notZero && notEqual){
return a["UserID"] - b["UserID"];
} else {
return a["OkeyTablePlayerChairNumber"] - b["OkeyTablePlayerChairNumber"];
}
}
var sorted = json.sort(idSort);
Results:
[ { Username: 'Erçin', UserID: 1, OkeyTablePlayerChairNumber: 3 },
{ Username: 'Mehmet', UserID: 2, OkeyTablePlayerChairNumber: 1 },
{ Username: null, UserID: 0, OkeyTablePlayerChairNumber: 2 },
{ Username: null, UserID: 0, OkeyTablePlayerChairNumber: 4 },
{ Username: null, UserID: 0, OkeyTablePlayerChairNumber: 5 },
{ Username: null, UserID: 0, OkeyTablePlayerChairNumber: 6 },
{ Username: null, UserID: 0, OkeyTablePlayerChairNumber: 7 },
{ Username: null, UserID: 0, OkeyTablePlayerChairNumber: 8 },
{ Username: null, UserID: 0, OkeyTablePlayerChairNumber: 9 } ]
In action: http://repl.it/XZm/1

Categories

Resources