skip to Main Content

In Angular, I have two JSONs, one JSON(A) consist of entire vehicle records whereas other JSON (B) consist of ids. I want to return only match ids records from JSON (A). Below are details

JSON (A)

{
         "id":100,
         "brand":"Tes1",
         "vname":"Testname1",
 },
 {
         "id":200,
         "brand":"Tes2",
         "vname":"Testname2",
 },
{
         "id":300,
         "brand":"Tes3",
         "vname":"Testname3",
 }

JSON (B)

{
         "id":100
 },
{
         "id":300
 },

Expected Output after aaply filter to (A) by (B)

{
         "id":100,
         "brand":"Tes1",
         "vname":"Testname1",
 },
{
         "id":300,
         "brand":"Tes3",
         "vname":"Testname3",
 },

2

Answers


  1. You can use Array.prorotype.filter() combined with Array.prototype.some()

    Code:

    const jsonA = [{id: 100,brand: 'Tes1',vname: 'Testname1',},{id: 200,brand: 'Tes2',vname: 'Testname2',},{id: 300,brand: 'Tes3',vname: 'Testname3',},]
    
    const jsonB = [
      {
        id: 100,
      },
      {
        id: 300,
      },
    ]
    
    const filteredData = jsonA.filter((itemA) => jsonB.some((itemB) => itemB.id === itemA.id))
    
    console.log(filteredData)
    Login or Signup to reply.
  2. If you are conserned about performance then filter&some can impact your app as it contains nested loops. In that case you can rely on lookup

    const jsonA = [{id: 100,brand: 'Tes1',vname: 'Testname1',}, {id: 200,brand: 'Tes2',vname: 'Testname2',}, {id: 300,brand: 'Tes3',vname: 'Testname3',}]
    
    const jsonB = [{id: 100}, {id: 300}]
    
    const map = new Map(jsonB.map(obj => [obj.id, obj]));
    const intersection = jsonA.filter(obj => map.has(obj.id));
    
    console.log(intersection);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search