Post(s) tagged JavaScript

How to convert JavaScript array of object to array of string

Using the JavaScript map method easily convert JavaScript array of object to array of string

var itemList = [
    { id: 1000, name: 'Name 1' },
    { id: 1001, name: 'Name 2' },
    { id: 1002, name: 'Name 3' }
];

var idList = itemList.map(function (item) {
    return item['id'];
});

var nameList = itemList.map(function (item) {
    return item['name'];
});

console.log(idList);
console.log(nameList);

//output: [1000, 1001, 1002]
//output: ['Name 1', 'Name 2', 'Name 3']


Posted on January 30, 2022

Javascript sort an array based on another array

Data array

var dataArray = [
    { name: 'Alberta Owen', id: 1 },
    { name: 'Jimmy Murphy', id: 2 },
    { name: 'Jerald Roberson', id: 3 },
    { name: 'Roosevelt Douglas', id: 4 },
    { name: 'Mark Ramsey', id: 5 }
]

Sort array

var sortArray = ['Mark Ramsey', 'Jimmy Murphy', 'Alberta Owen'];

Sorting

dataArray.sort((a, b) => sortArray.indexOf(a) - sortArray.indexOf(b));


Posted on February 10, 2022

Best and easy way to use Async parallel in Node Js

Using the below method can get the results for each task very easily

async.parallel({
    firstTask: function (callback) {
        callback(null, 'fist task result');
    },
    secondTask: function (callback) {
        callback(null, 'second task result');
    }
}, function (err, results) {
    // results now equals to: results.firstTask: 'fist task result', results.secondTask: 'second task result'
});


Posted on February 10, 2022

npm - EPERM: operation not permitted on Windows

npm start command encounters An unhandled exception occurred: EPERM: operation not permitted

Here is the simplest way I fixed the bug.

Open .npmrc file located on C:\Users\<user name>\.npmrc

Change the path of prefix= to prefix=C:\Users\<user name>\AppData\Roaming\npm

Delete node_modules folder and run npm install command

Then run npm start command


Posted on February 20, 2022

Import JSON array from local file to Typescript array

The sample JSON file content (data.json):

[
  {
    "FirstName": "Joe",
    "UserId": 1
  },
  {
    "FirstName": "Jack",
    "UserId": 2
  }
]

Next, add appropriate resolveJsonModule entry to tsconfig.json entry

{
    "compilerOptions": {  
      "esModuleInterop": true
      "resolveJsonModule": true
    } 
}

Finally, import the data and access it using the below code.

import data from './data.json';

interface Person{
    FirstName: string,
    UserId: number,
}

const userArray:User[] = data as User[];


Posted on February 27, 2022

Next.js create a custom server with HTTP proxy to external server

First, create a server file named server.js and paste the below code to that file.

const next = require('next');
const dev = process.env.NODE_ENV !== 'production'
const hostname = 'localhost';
const port = 3000;
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
var express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

app.prepare().then(() => {
    const server = express();
    server.use('/api', createProxyMiddleware({ target: 'https://samprix.com', changeOrigin: true, }));    

    server.all('*', (req, res) => handle(req, res));

    server.listen(port, err => {
        if (err) throw err;
        console.log(`> Ready on http://localhost:${port}`);
    });
})

Then build the Next.js using the below command

NODE_ENV=production next build

After the build run the server js file using the below command

NODE_ENV=production node -r esm node server.js

For more information about the Next.js custom server refer to this doc.


Posted on March 04, 2022

How to exclude Typescript build .js, .js.map files from the project on VS Code

You can exclude the Typescript build .js .js.map from VS Code using the below steps.
Add the below code to .vscode folder settings.json file, this will exclude .js and.js when the typescript file present for the corresponding .js and .js.map file

{
    "files.exclude": {
        "**/*.js": {
            "when": "$(basename).ts"
        },
        "**/*.js.map": {
            "when": "$(basename)"
        }
    }
}


Posted on March 24, 2022
Sponsors