Home > Enterprise >  Find the object with specific product type and get id from URL and join by comma using Javascript
Find the object with specific product type and get id from URL and join by comma using Javascript

Time:02-03

I have set of array of objects containing url, product type where I want to filter the producttype and split the id from url and join by comma

if productType is "ESJ:001" I want to pass the id else if prductType is "ESJ003" I want to pass the empty data Also if there is "undefined" I want to pass it an empty.

let obj= [ 
  { url: 'http://localhost:3000/redApi?id=001&name=abc&[email protected]', productType:'ESJ001'}
{ url: 'http://localhost:3000/redApi?id=005&name=abc&[email protected]', productType:'ESJ001'}
  { url: 'http://localhost:3000/redApi?id=002&name=xyz&[email protected]' productType:'ESJ003'}
  { url: 'http://localhost:3000/redApi?id=undefined&name=pqr&[email protected]'}
]

Expected output:

001,005,,

Here is my code I am able to get 001,005 but not sure how to include empty data for ESJ003 and undefined

Output I am getting

001,005

expected output

001,005,,

let obj= [ 
  { url: 'http://localhost:3000/redApi?id=001&name=abc&[email protected]', productType:'ESJ001'},
{ url: 'http://localhost:3000/redApi?id=005&name=abc&[email protected]', productType:'ESJ001'},
  { url: 'http://localhost:3000/redApi?id=002&name=xyz&[email protected]', productType:'ESJ003'},
  { url: 'http://localhost:3000/redApiid=undefined&name=pqr&[email protected]'}
]
let urlIds = obj.filter(x=>x.productType === 'ESJ001').map(x => new URL(x?.url).searchParams.get('id'));
    urlIds = urlIds.map(value => value === "undefined" ? "" : value);
    let joinedUrlIds = urlIds.join(',');
    console.log(joinedUrlIds)

CodePudding user response:

You are getting only two values because you're filtering out those that don't match x.productType === 'ESJ001'. To get the expected output, you can do this:

let obj = [{
    url: 'http://localhost:3000/redApi?id=001&name=abc&[email protected]',
    productType: 'ESJ001'
  },
  {
    url: 'http://localhost:3000/redApi?id=005&name=abc&[email protected]',
    productType: 'ESJ001'
  },
  {
    url: 'http://localhost:3000/redApi?id=002&name=xyz&[email protected]',
    productType: 'ESJ003'
  },
  {
    url: 'http://localhost:3000/redApiid=undefined&name=pqr&[email protected]'
  }
]
const urlIds = obj.map(x => (x.productType === 'ESJ001' ? new URL(x?.url).searchParams.get('id') : ''))
  .map(value => value === 'undefined' ? '' : value);
const joinedUrlIds = urlIds.join();
console.log(joinedUrlIds)

CodePudding user response:

I think you just need to do something like this, even simpler code:

const getID = (url) => new URL(url).searchParams.get('id')
const data = obj.map(data => data.productType === 'ESJ001' ? getID(data.url) : 
"")

console.log(data)

I think your filter is problematic here

  • Related